diff --git a/build.gradle.kts b/build.gradle.kts index 5bd2f75..abe776e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -75,14 +75,24 @@ tasks.test { } val generateTelegramBotApi by tasks.registering(GenerateTelegramBotApiTask::class) { + group = "telegram" apiSpecFile = layout.projectDirectory.file("api-spec/telegram-bot-api.html") packageName = "me.alllex.tbot.api.model" telegramClientPackage = "me.alllex.tbot.api.client" outputDirectory = layout.projectDirectory.dir("src/main/generated-kotlin") } -kotlin.sourceSets.main { - kotlin.srcDir(generateTelegramBotApi) +kotlin.sourceSets { + all { + languageSettings { + optIn("me.alllex.tbot.api.client.BotKitInternalAPI") + optIn("kotlinx.serialization.ExperimentalSerializationApi") + optIn("kotlinx.coroutines.ExperimentalCoroutinesApi") + } + } + main { + kotlin.srcDir(generateTelegramBotApi) + } } kotlin.compilerOptions { diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index 616c23d..8acfb4b 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -7,8 +7,8 @@ repositories { } dependencies { - implementation("org.jsoup:jsoup:1.16.1") - implementation("me.alllex.parsus:parsus-jvm:0.5.5") + implementation("org.jsoup:jsoup:1.17.1") + implementation("me.alllex.parsus:parsus-jvm:0.6.0") } val updateApiSpec by tasks.registering { diff --git a/buildSrc/src/main/kotlin/GenerateTelegramBotApiTask.kt b/buildSrc/src/main/kotlin/GenerateTelegramBotApiTask.kt index 3038f51..63ec245 100644 --- a/buildSrc/src/main/kotlin/GenerateTelegramBotApiTask.kt +++ b/buildSrc/src/main/kotlin/GenerateTelegramBotApiTask.kt @@ -3,7 +3,13 @@ import org.gradle.api.DefaultTask import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.Property -import org.gradle.api.tasks.* +import org.gradle.api.tasks.CacheableTask +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.InputFile +import org.gradle.api.tasks.OutputDirectory +import org.gradle.api.tasks.PathSensitive +import org.gradle.api.tasks.PathSensitivity +import org.gradle.api.tasks.TaskAction @CacheableTask abstract class GenerateTelegramBotApiTask : DefaultTask() { diff --git a/buildSrc/src/main/kotlin/me/alllex/tbot/apigen/BotApiDefinitionParser.kt b/buildSrc/src/main/kotlin/me/alllex/tbot/apigen/BotApiDefinitionParser.kt index da3ae1c..045caf4 100644 --- a/buildSrc/src/main/kotlin/me/alllex/tbot/apigen/BotApiDefinitionParser.kt +++ b/buildSrc/src/main/kotlin/me/alllex/tbot/apigen/BotApiDefinitionParser.kt @@ -1,6 +1,12 @@ package me.alllex.tbot.apigen -import me.alllex.parsus.parser.* +import me.alllex.parsus.parser.Grammar +import me.alllex.parsus.parser.ParseException +import me.alllex.parsus.parser.getOrElse +import me.alllex.parsus.parser.map +import me.alllex.parsus.parser.or +import me.alllex.parsus.parser.parser +import me.alllex.parsus.parser.repeatOneOrMore import me.alllex.parsus.token.regexToken import org.jsoup.Jsoup import org.jsoup.nodes.Element diff --git a/buildSrc/src/main/kotlin/me/alllex/tbot/apigen/BotApiGenerator.kt b/buildSrc/src/main/kotlin/me/alllex/tbot/apigen/BotApiGenerator.kt index f0903fd..9730295 100644 --- a/buildSrc/src/main/kotlin/me/alllex/tbot/apigen/BotApiGenerator.kt +++ b/buildSrc/src/main/kotlin/me/alllex/tbot/apigen/BotApiGenerator.kt @@ -554,20 +554,18 @@ class BotApiGenerator { append("requestBody: $requestTypeName") } appendLine("): TelegramResponse<${returnType.value}> =") - appendLine(" executeRequest(\"$apiMethodName\", ${if (hasParams) "requestBody" else "null"}) {") - appendLine(" httpClient.$httpMethod {") - appendLine(" url {") - appendLine(" protocol = apiProtocol") - appendLine(" host = apiHost") - appendLine(" port = apiPort") - appendLine(" path(\"bot\$apiToken\", \"$apiMethodName\")") - appendLine(" }") + appendLine(" httpClient.$httpMethod {") + appendLine(" url {") + appendLine(" protocol = apiProtocol") + appendLine(" host = apiHost") + appendLine(" port = apiPort") + appendLine(" path(\"bot\$apiToken\", \"$apiMethodName\")") + appendLine(" }") if (hasParams) { - appendLine(" contentType(ContentType.Application.Json)") - appendLine(" setBody(requestBody)") + appendLine(" contentType(ContentType.Application.Json)") + appendLine(" setBody(requestBody)") } - appendLine(" }.body()") - appendLine(" }") + appendLine(" }.body()") } val tryMethodSourceCode = buildString { @@ -738,9 +736,9 @@ class BotApiGenerator { } appendLine(" */") appendLine("@Serializable(with = ${name}Serializer::class)") - appendLine("sealed class $name {") - appendLine(" abstract val updateId: Long") - appendLine(" abstract val updateType: UpdateType") + appendLine("sealed interface $name {") + appendLine(" val updateId: Long") + appendLine(" val updateType: UpdateType") appendLine("}") for (updateField in types) { appendLine() @@ -749,7 +747,7 @@ class BotApiGenerator { appendLine("data class ${updateField.updateTypeName()}(") appendLine(" override val updateId: Long,") appendLine(" val ${updateField.name}: ${updateField.type},") - appendLine("): $name() {") + appendLine("): $name {") appendLine(" override val updateType: UpdateType get() = UpdateType.${updateField.enumValue()}") appendLine("}") } @@ -798,7 +796,7 @@ class BotApiGenerator { appendLine("@JsonClassDiscriminator(\"$discriminatorFieldName\")") } - appendLine("sealed class ${name.value}") + appendLine("sealed interface ${name.value}") if (discriminatorFieldName == null) { val avoidFields = setOf("description") @@ -872,7 +870,7 @@ class BotApiGenerator { append("data object ") append(typeName.value) if (sealedParentName != null) { - append(" : ${sealedParentName.value}()") + append(" : ${sealedParentName.value}") } appendLine() } else { @@ -884,7 +882,7 @@ class BotApiGenerator { append(")") if (sealedParentName != null) { - append(" : ${sealedParentName.value}()") + append(" : ${sealedParentName.value}") } appendLine(" {") appendLine(" ${generateDebugToString(typeName.value, trueFields)}") diff --git a/buildSrc/src/main/kotlin/me/alllex/tbot/apigen/util.kt b/buildSrc/src/main/kotlin/me/alllex/tbot/apigen/util.kt index 753e937..2141321 100644 --- a/buildSrc/src/main/kotlin/me/alllex/tbot/apigen/util.kt +++ b/buildSrc/src/main/kotlin/me/alllex/tbot/apigen/util.kt @@ -1,6 +1,6 @@ package me.alllex.tbot.apigen -import java.util.* +import java.util.Locale /** diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index bc6957b..d9063fc 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,12 +1,12 @@ [versions] jdkTarget = "8" jvmToolchain = "21" -kotlinTarget = "1.9.0" -kotlinPlugin = "1.9.10" -kotlinx-coroutines = "1.6.4" -kotlinx-serialization = "1.5.1" -ktor = "2.3.2" -log4j = "2.20.0" +kotlinTarget = "1.9.20" +kotlinPlugin = "1.9.20" +kotlinx-coroutines = "1.7.3" +kotlinx-serialization = "1.6.2" +ktor = "2.3.7" +log4j = "2.22.0" junit5 = "5.10.0" [libraries] diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index ac72c34..1af9e09 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/src/main/generated-kotlin/me/alllex/tbot/api/model/TryRequestMethods.kt b/src/main/generated-kotlin/me/alllex/tbot/api/model/TryRequestMethods.kt index 672902e..660f626 100644 --- a/src/main/generated-kotlin/me/alllex/tbot/api/model/TryRequestMethods.kt +++ b/src/main/generated-kotlin/me/alllex/tbot/api/model/TryRequestMethods.kt @@ -10,18 +10,16 @@ import me.alllex.tbot.api.client.* * Use this method to receive incoming updates using long polling (wiki). Returns an Array of Update objects. */ suspend fun TelegramBotApiClient.tryGetUpdates(requestBody: GetUpdatesRequest): TelegramResponse> = - executeRequest("getUpdates", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getUpdates") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getUpdates") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success. @@ -29,163 +27,143 @@ suspend fun TelegramBotApiClient.tryGetUpdates(requestBody: GetUpdatesRequest): * If you'd like to make sure that the webhook was set by you, you can specify secret data in the parameter secret_token. If specified, the request will contain a header “X-Telegram-Bot-Api-Secret-Token” with the secret token as content. */ suspend fun TelegramBotApiClient.trySetWebhook(requestBody: SetWebhookRequest): TelegramResponse = - executeRequest("setWebhook", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setWebhook") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setWebhook") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. */ suspend fun TelegramBotApiClient.tryDeleteWebhook(requestBody: DeleteWebhookRequest): TelegramResponse = - executeRequest("deleteWebhook", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "deleteWebhook") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "deleteWebhook") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty. */ suspend fun TelegramBotApiClient.tryGetWebhookInfo(): TelegramResponse = - executeRequest("getWebhookInfo", null) { - httpClient.get { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getWebhookInfo") - } - }.body() - } + httpClient.get { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getWebhookInfo") + } + }.body() /** * A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a User object. */ suspend fun TelegramBotApiClient.tryGetMe(): TelegramResponse = - executeRequest("getMe", null) { - httpClient.get { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getMe") - } - }.body() - } + httpClient.get { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getMe") + } + }.body() /** * Use this method to log out from the cloud Bot API server before launching the bot locally. You must log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes. Returns True on success. Requires no parameters. */ suspend fun TelegramBotApiClient.tryLogOut(): TelegramResponse = - executeRequest("logOut", null) { - httpClient.get { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "logOut") - } - }.body() - } + httpClient.get { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "logOut") + } + }.body() /** * Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns True on success. Requires no parameters. */ suspend fun TelegramBotApiClient.tryClose(): TelegramResponse = - executeRequest("close", null) { - httpClient.get { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "close") - } - }.body() - } + httpClient.get { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "close") + } + }.body() /** * Use this method to send text messages. On success, the sent Message is returned. */ suspend fun TelegramBotApiClient.trySendMessage(requestBody: SendMessageRequest): TelegramResponse = - executeRequest("sendMessage", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendMessage") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendMessage") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to forward messages of any kind. Service messages can't be forwarded. On success, the sent Message is returned. */ suspend fun TelegramBotApiClient.tryForwardMessage(requestBody: ForwardMessageRequest): TelegramResponse = - executeRequest("forwardMessage", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "forwardMessage") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "forwardMessage") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to copy messages of any kind. Service messages and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. */ suspend fun TelegramBotApiClient.tryCopyMessage(requestBody: CopyMessageRequest): TelegramResponse = - executeRequest("copyMessage", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "copyMessage") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "copyMessage") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send photos. On success, the sent Message is returned. */ suspend fun TelegramBotApiClient.trySendPhoto(requestBody: SendPhotoRequest): TelegramResponse = - executeRequest("sendPhoto", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendPhoto") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendPhoto") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. @@ -193,205 +171,181 @@ suspend fun TelegramBotApiClient.trySendPhoto(requestBody: SendPhotoRequest): Te * For sending voice messages, use the sendVoice method instead. */ suspend fun TelegramBotApiClient.trySendAudio(requestBody: SendAudioRequest): TelegramResponse = - executeRequest("sendAudio", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendAudio") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendAudio") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. */ suspend fun TelegramBotApiClient.trySendDocument(requestBody: SendDocumentRequest): TelegramResponse = - executeRequest("sendDocument", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendDocument") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendDocument") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. */ suspend fun TelegramBotApiClient.trySendVideo(requestBody: SendVideoRequest): TelegramResponse = - executeRequest("sendVideo", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendVideo") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendVideo") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. */ suspend fun TelegramBotApiClient.trySendAnimation(requestBody: SendAnimationRequest): TelegramResponse = - executeRequest("sendAnimation", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendAnimation") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendAnimation") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. */ suspend fun TelegramBotApiClient.trySendVoice(requestBody: SendVoiceRequest): TelegramResponse = - executeRequest("sendVoice", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendVoice") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendVoice") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned. */ suspend fun TelegramBotApiClient.trySendVideoNote(requestBody: SendVideoNoteRequest): TelegramResponse = - executeRequest("sendVideoNote", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendVideoNote") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendVideoNote") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Messages that were sent is returned. */ suspend fun TelegramBotApiClient.trySendMediaGroup(requestBody: SendMediaGroupRequest): TelegramResponse> = - executeRequest("sendMediaGroup", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendMediaGroup") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendMediaGroup") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send point on the map. On success, the sent Message is returned. */ suspend fun TelegramBotApiClient.trySendLocation(requestBody: SendLocationRequest): TelegramResponse = - executeRequest("sendLocation", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendLocation") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendLocation") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send information about a venue. On success, the sent Message is returned. */ suspend fun TelegramBotApiClient.trySendVenue(requestBody: SendVenueRequest): TelegramResponse = - executeRequest("sendVenue", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendVenue") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendVenue") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send phone contacts. On success, the sent Message is returned. */ suspend fun TelegramBotApiClient.trySendContact(requestBody: SendContactRequest): TelegramResponse = - executeRequest("sendContact", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendContact") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendContact") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send a native poll. On success, the sent Message is returned. */ suspend fun TelegramBotApiClient.trySendPoll(requestBody: SendPollRequest): TelegramResponse = - executeRequest("sendPoll", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendPoll") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendPoll") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned. */ suspend fun TelegramBotApiClient.trySendDice(requestBody: SendDiceRequest): TelegramResponse = - executeRequest("sendDice", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendDice") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendDice") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success. @@ -401,747 +355,659 @@ suspend fun TelegramBotApiClient.trySendDice(requestBody: SendDiceRequest): Tele * We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive. */ suspend fun TelegramBotApiClient.trySendChatAction(requestBody: SendChatActionRequest): TelegramResponse = - executeRequest("sendChatAction", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendChatAction") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendChatAction") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object. */ suspend fun TelegramBotApiClient.tryGetUserProfilePhotos(requestBody: GetUserProfilePhotosRequest): TelegramResponse = - executeRequest("getUserProfilePhotos", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getUserProfilePhotos") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getUserProfilePhotos") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get basic information about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot/, where is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again. */ suspend fun TelegramBotApiClient.tryGetFile(requestBody: GetFileRequest): TelegramResponse = - executeRequest("getFile", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getFile") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getFile") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. */ suspend fun TelegramBotApiClient.tryBanChatMember(requestBody: BanChatMemberRequest): TelegramResponse = - executeRequest("banChatMember", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "banChatMember") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "banChatMember") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to unban a previously banned user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success. */ suspend fun TelegramBotApiClient.tryUnbanChatMember(requestBody: UnbanChatMemberRequest): TelegramResponse = - executeRequest("unbanChatMember", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "unbanChatMember") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "unbanChatMember") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success. */ suspend fun TelegramBotApiClient.tryRestrictChatMember(requestBody: RestrictChatMemberRequest): TelegramResponse = - executeRequest("restrictChatMember", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "restrictChatMember") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "restrictChatMember") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success. */ suspend fun TelegramBotApiClient.tryPromoteChatMember(requestBody: PromoteChatMemberRequest): TelegramResponse = - executeRequest("promoteChatMember", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "promoteChatMember") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "promoteChatMember") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success. */ suspend fun TelegramBotApiClient.trySetChatAdministratorCustomTitle(requestBody: SetChatAdministratorCustomTitleRequest): TelegramResponse = - executeRequest("setChatAdministratorCustomTitle", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setChatAdministratorCustomTitle") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setChatAdministratorCustomTitle") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success. */ suspend fun TelegramBotApiClient.tryBanChatSenderChat(requestBody: BanChatSenderChatRequest): TelegramResponse = - executeRequest("banChatSenderChat", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "banChatSenderChat") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "banChatSenderChat") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success. */ suspend fun TelegramBotApiClient.tryUnbanChatSenderChat(requestBody: UnbanChatSenderChatRequest): TelegramResponse = - executeRequest("unbanChatSenderChat", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "unbanChatSenderChat") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "unbanChatSenderChat") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members administrator rights. Returns True on success. */ suspend fun TelegramBotApiClient.trySetChatPermissions(requestBody: SetChatPermissionsRequest): TelegramResponse = - executeRequest("setChatPermissions", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setChatPermissions") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setChatPermissions") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as String on success. */ suspend fun TelegramBotApiClient.tryExportChatInviteLink(requestBody: ExportChatInviteLinkRequest): TelegramResponse = - executeRequest("exportChatInviteLink", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "exportChatInviteLink") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "exportChatInviteLink") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object. */ suspend fun TelegramBotApiClient.tryCreateChatInviteLink(requestBody: CreateChatInviteLinkRequest): TelegramResponse = - executeRequest("createChatInviteLink", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "createChatInviteLink") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "createChatInviteLink") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a ChatInviteLink object. */ suspend fun TelegramBotApiClient.tryEditChatInviteLink(requestBody: EditChatInviteLinkRequest): TelegramResponse = - executeRequest("editChatInviteLink", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "editChatInviteLink") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "editChatInviteLink") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as ChatInviteLink object. */ suspend fun TelegramBotApiClient.tryRevokeChatInviteLink(requestBody: RevokeChatInviteLinkRequest): TelegramResponse = - executeRequest("revokeChatInviteLink", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "revokeChatInviteLink") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "revokeChatInviteLink") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success. */ suspend fun TelegramBotApiClient.tryApproveChatJoinRequest(requestBody: ApproveChatJoinRequestRequest): TelegramResponse = - executeRequest("approveChatJoinRequest", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "approveChatJoinRequest") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "approveChatJoinRequest") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success. */ suspend fun TelegramBotApiClient.tryDeclineChatJoinRequest(requestBody: DeclineChatJoinRequestRequest): TelegramResponse = - executeRequest("declineChatJoinRequest", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "declineChatJoinRequest") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "declineChatJoinRequest") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. */ suspend fun TelegramBotApiClient.trySetChatPhoto(requestBody: SetChatPhotoRequest): TelegramResponse = - executeRequest("setChatPhoto", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setChatPhoto") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setChatPhoto") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. */ suspend fun TelegramBotApiClient.tryDeleteChatPhoto(requestBody: DeleteChatPhotoRequest): TelegramResponse = - executeRequest("deleteChatPhoto", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "deleteChatPhoto") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "deleteChatPhoto") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. */ suspend fun TelegramBotApiClient.trySetChatTitle(requestBody: SetChatTitleRequest): TelegramResponse = - executeRequest("setChatTitle", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setChatTitle") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setChatTitle") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. */ suspend fun TelegramBotApiClient.trySetChatDescription(requestBody: SetChatDescriptionRequest): TelegramResponse = - executeRequest("setChatDescription", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setChatDescription") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setChatDescription") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to add a message to the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success. */ suspend fun TelegramBotApiClient.tryPinChatMessage(requestBody: PinChatMessageRequest): TelegramResponse = - executeRequest("pinChatMessage", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "pinChatMessage") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "pinChatMessage") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to remove a message from the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success. */ suspend fun TelegramBotApiClient.tryUnpinChatMessage(requestBody: UnpinChatMessageRequest): TelegramResponse = - executeRequest("unpinChatMessage", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "unpinChatMessage") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "unpinChatMessage") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to clear the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success. */ suspend fun TelegramBotApiClient.tryUnpinAllChatMessages(requestBody: UnpinAllChatMessagesRequest): TelegramResponse = - executeRequest("unpinAllChatMessages", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "unpinAllChatMessages") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "unpinAllChatMessages") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method for your bot to leave a group, supergroup or channel. Returns True on success. */ suspend fun TelegramBotApiClient.tryLeaveChat(requestBody: LeaveChatRequest): TelegramResponse = - executeRequest("leaveChat", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "leaveChat") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "leaveChat") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success. */ suspend fun TelegramBotApiClient.tryGetChat(requestBody: GetChatRequest): TelegramResponse = - executeRequest("getChat", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getChat") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getChat") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get a list of administrators in a chat, which aren't bots. Returns an Array of ChatMember objects. */ suspend fun TelegramBotApiClient.tryGetChatAdministrators(requestBody: GetChatAdministratorsRequest): TelegramResponse> = - executeRequest("getChatAdministrators", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getChatAdministrators") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getChatAdministrators") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get the number of members in a chat. Returns Int on success. */ suspend fun TelegramBotApiClient.tryGetChatMemberCount(requestBody: GetChatMemberCountRequest): TelegramResponse = - executeRequest("getChatMemberCount", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getChatMemberCount") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getChatMemberCount") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get information about a member of a chat. The method is only guaranteed to work for other users if the bot is an administrator in the chat. Returns a ChatMember object on success. */ suspend fun TelegramBotApiClient.tryGetChatMember(requestBody: GetChatMemberRequest): TelegramResponse = - executeRequest("getChatMember", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getChatMember") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getChatMember") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success. */ suspend fun TelegramBotApiClient.trySetChatStickerSet(requestBody: SetChatStickerSetRequest): TelegramResponse = - executeRequest("setChatStickerSet", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setChatStickerSet") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setChatStickerSet") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success. */ suspend fun TelegramBotApiClient.tryDeleteChatStickerSet(requestBody: DeleteChatStickerSetRequest): TelegramResponse = - executeRequest("deleteChatStickerSet", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "deleteChatStickerSet") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "deleteChatStickerSet") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user. Requires no parameters. Returns an Array of Sticker objects. */ suspend fun TelegramBotApiClient.tryGetForumTopicIconStickers(): TelegramResponse> = - executeRequest("getForumTopicIconStickers", null) { - httpClient.get { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getForumTopicIconStickers") - } - }.body() - } + httpClient.get { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getForumTopicIconStickers") + } + }.body() /** * Use this method to create a topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns information about the created topic as a ForumTopic object. */ suspend fun TelegramBotApiClient.tryCreateForumTopic(requestBody: CreateForumTopicRequest): TelegramResponse = - executeRequest("createForumTopic", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "createForumTopic") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "createForumTopic") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to edit name and icon of a topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success. */ suspend fun TelegramBotApiClient.tryEditForumTopic(requestBody: EditForumTopicRequest): TelegramResponse = - executeRequest("editForumTopic", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "editForumTopic") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "editForumTopic") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to close an open topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success. */ suspend fun TelegramBotApiClient.tryCloseForumTopic(requestBody: CloseForumTopicRequest): TelegramResponse = - executeRequest("closeForumTopic", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "closeForumTopic") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "closeForumTopic") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to reopen a closed topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success. */ suspend fun TelegramBotApiClient.tryReopenForumTopic(requestBody: ReopenForumTopicRequest): TelegramResponse = - executeRequest("reopenForumTopic", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "reopenForumTopic") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "reopenForumTopic") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to delete a forum topic along with all its messages in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_delete_messages administrator rights. Returns True on success. */ suspend fun TelegramBotApiClient.tryDeleteForumTopic(requestBody: DeleteForumTopicRequest): TelegramResponse = - executeRequest("deleteForumTopic", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "deleteForumTopic") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "deleteForumTopic") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to clear the list of pinned messages in a forum topic. The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success. */ suspend fun TelegramBotApiClient.tryUnpinAllForumTopicMessages(requestBody: UnpinAllForumTopicMessagesRequest): TelegramResponse = - executeRequest("unpinAllForumTopicMessages", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "unpinAllForumTopicMessages") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "unpinAllForumTopicMessages") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to edit the name of the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have can_manage_topics administrator rights. Returns True on success. */ suspend fun TelegramBotApiClient.tryEditGeneralForumTopic(requestBody: EditGeneralForumTopicRequest): TelegramResponse = - executeRequest("editGeneralForumTopic", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "editGeneralForumTopic") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "editGeneralForumTopic") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to close an open 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success. */ suspend fun TelegramBotApiClient.tryCloseGeneralForumTopic(requestBody: CloseGeneralForumTopicRequest): TelegramResponse = - executeRequest("closeGeneralForumTopic", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "closeGeneralForumTopic") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "closeGeneralForumTopic") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to reopen a closed 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically unhidden if it was hidden. Returns True on success. */ suspend fun TelegramBotApiClient.tryReopenGeneralForumTopic(requestBody: ReopenGeneralForumTopicRequest): TelegramResponse = - executeRequest("reopenGeneralForumTopic", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "reopenGeneralForumTopic") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "reopenGeneralForumTopic") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to hide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically closed if it was open. Returns True on success. */ suspend fun TelegramBotApiClient.tryHideGeneralForumTopic(requestBody: HideGeneralForumTopicRequest): TelegramResponse = - executeRequest("hideGeneralForumTopic", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "hideGeneralForumTopic") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "hideGeneralForumTopic") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to unhide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success. */ suspend fun TelegramBotApiClient.tryUnhideGeneralForumTopic(requestBody: UnhideGeneralForumTopicRequest): TelegramResponse = - executeRequest("unhideGeneralForumTopic", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "unhideGeneralForumTopic") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "unhideGeneralForumTopic") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to clear the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success. */ suspend fun TelegramBotApiClient.tryUnpinAllGeneralForumTopicMessages(requestBody: UnpinAllGeneralForumTopicMessagesRequest): TelegramResponse = - executeRequest("unpinAllGeneralForumTopicMessages", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "unpinAllGeneralForumTopicMessages") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "unpinAllGeneralForumTopicMessages") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. @@ -1149,834 +1015,736 @@ suspend fun TelegramBotApiClient.tryUnpinAllGeneralForumTopicMessages(requestBod * Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @BotFather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter. */ suspend fun TelegramBotApiClient.tryAnswerCallbackQuery(requestBody: AnswerCallbackQueryRequest): TelegramResponse = - executeRequest("answerCallbackQuery", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "answerCallbackQuery") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "answerCallbackQuery") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to change the list of the bot's commands. See this manual for more details about bot commands. Returns True on success. */ suspend fun TelegramBotApiClient.trySetMyCommands(requestBody: SetMyCommandsRequest): TelegramResponse = - executeRequest("setMyCommands", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setMyCommands") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setMyCommands") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns True on success. */ suspend fun TelegramBotApiClient.tryDeleteMyCommands(requestBody: DeleteMyCommandsRequest): TelegramResponse = - executeRequest("deleteMyCommands", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "deleteMyCommands") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "deleteMyCommands") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get the current list of the bot's commands for the given scope and user language. Returns an Array of BotCommand objects. If commands aren't set, an empty list is returned. */ suspend fun TelegramBotApiClient.tryGetMyCommands(requestBody: GetMyCommandsRequest): TelegramResponse> = - executeRequest("getMyCommands", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getMyCommands") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getMyCommands") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to change the bot's name. Returns True on success. */ suspend fun TelegramBotApiClient.trySetMyName(requestBody: SetMyNameRequest): TelegramResponse = - executeRequest("setMyName", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setMyName") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setMyName") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get the current bot name for the given user language. Returns BotName on success. */ suspend fun TelegramBotApiClient.tryGetMyName(requestBody: GetMyNameRequest): TelegramResponse = - executeRequest("getMyName", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getMyName") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getMyName") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty. Returns True on success. */ suspend fun TelegramBotApiClient.trySetMyDescription(requestBody: SetMyDescriptionRequest): TelegramResponse = - executeRequest("setMyDescription", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setMyDescription") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setMyDescription") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get the current bot description for the given user language. Returns BotDescription on success. */ suspend fun TelegramBotApiClient.tryGetMyDescription(requestBody: GetMyDescriptionRequest): TelegramResponse = - executeRequest("getMyDescription", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getMyDescription") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getMyDescription") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot. Returns True on success. */ suspend fun TelegramBotApiClient.trySetMyShortDescription(requestBody: SetMyShortDescriptionRequest): TelegramResponse = - executeRequest("setMyShortDescription", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setMyShortDescription") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setMyShortDescription") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get the current bot short description for the given user language. Returns BotShortDescription on success. */ suspend fun TelegramBotApiClient.tryGetMyShortDescription(requestBody: GetMyShortDescriptionRequest): TelegramResponse = - executeRequest("getMyShortDescription", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getMyShortDescription") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getMyShortDescription") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success. */ suspend fun TelegramBotApiClient.trySetChatMenuButton(requestBody: SetChatMenuButtonRequest): TelegramResponse = - executeRequest("setChatMenuButton", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setChatMenuButton") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setChatMenuButton") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success. */ suspend fun TelegramBotApiClient.tryGetChatMenuButton(requestBody: GetChatMenuButtonRequest): TelegramResponse = - executeRequest("getChatMenuButton", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getChatMenuButton") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getChatMenuButton") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are free to modify the list before adding the bot. Returns True on success. */ suspend fun TelegramBotApiClient.trySetMyDefaultAdministratorRights(requestBody: SetMyDefaultAdministratorRightsRequest): TelegramResponse = - executeRequest("setMyDefaultAdministratorRights", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setMyDefaultAdministratorRights") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setMyDefaultAdministratorRights") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success. */ suspend fun TelegramBotApiClient.tryGetMyDefaultAdministratorRights(requestBody: GetMyDefaultAdministratorRightsRequest): TelegramResponse = - executeRequest("getMyDefaultAdministratorRights", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getMyDefaultAdministratorRights") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getMyDefaultAdministratorRights") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to edit text and game messages. On success the edited Message is returned. */ suspend fun TelegramBotApiClient.tryEditMessageText(requestBody: EditMessageTextRequest): TelegramResponse = - executeRequest("editMessageText", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "editMessageText") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "editMessageText") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to edit text and game messages. On success True is returned. */ suspend fun TelegramBotApiClient.tryEditInlineMessageText(requestBody: EditMessageTextRequest): TelegramResponse = - executeRequest("editMessageText", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "editMessageText") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "editMessageText") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to edit captions of messages. On success the edited Message is returned. */ suspend fun TelegramBotApiClient.tryEditMessageCaption(requestBody: EditMessageCaptionRequest): TelegramResponse = - executeRequest("editMessageCaption", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "editMessageCaption") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "editMessageCaption") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to edit captions of messages. On success True is returned. */ suspend fun TelegramBotApiClient.tryEditInlineMessageCaption(requestBody: EditMessageCaptionRequest): TelegramResponse = - executeRequest("editMessageCaption", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "editMessageCaption") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "editMessageCaption") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to edit animation, audio, document, photo, or video messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success the edited Message is returned. */ suspend fun TelegramBotApiClient.tryEditMessageMedia(requestBody: EditMessageMediaRequest): TelegramResponse = - executeRequest("editMessageMedia", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "editMessageMedia") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "editMessageMedia") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to edit animation, audio, document, photo, or video messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success True is returned. */ suspend fun TelegramBotApiClient.tryEditInlineMessageMedia(requestBody: EditMessageMediaRequest): TelegramResponse = - executeRequest("editMessageMedia", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "editMessageMedia") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "editMessageMedia") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success the edited Message is returned. */ suspend fun TelegramBotApiClient.tryEditMessageLiveLocation(requestBody: EditMessageLiveLocationRequest): TelegramResponse = - executeRequest("editMessageLiveLocation", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "editMessageLiveLocation") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "editMessageLiveLocation") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success True is returned. */ suspend fun TelegramBotApiClient.tryEditInlineMessageLiveLocation(requestBody: EditMessageLiveLocationRequest): TelegramResponse = - executeRequest("editMessageLiveLocation", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "editMessageLiveLocation") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "editMessageLiveLocation") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to stop updating a live location message before live_period expires. On success the edited Message is returned. */ suspend fun TelegramBotApiClient.tryStopMessageLiveLocation(requestBody: StopMessageLiveLocationRequest): TelegramResponse = - executeRequest("stopMessageLiveLocation", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "stopMessageLiveLocation") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "stopMessageLiveLocation") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to stop updating a live location message before live_period expires. On success True is returned. */ suspend fun TelegramBotApiClient.tryStopInlineMessageLiveLocation(requestBody: StopMessageLiveLocationRequest): TelegramResponse = - executeRequest("stopMessageLiveLocation", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "stopMessageLiveLocation") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "stopMessageLiveLocation") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to edit only the reply markup of messages. On success the edited Message is returned. */ suspend fun TelegramBotApiClient.tryEditMessageReplyMarkup(requestBody: EditMessageReplyMarkupRequest): TelegramResponse = - executeRequest("editMessageReplyMarkup", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "editMessageReplyMarkup") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "editMessageReplyMarkup") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to edit only the reply markup of messages. On success True is returned. */ suspend fun TelegramBotApiClient.tryEditInlineMessageReplyMarkup(requestBody: EditMessageReplyMarkupRequest): TelegramResponse = - executeRequest("editMessageReplyMarkup", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "editMessageReplyMarkup") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "editMessageReplyMarkup") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to stop a poll which was sent by the bot. On success, the stopped Poll is returned. */ suspend fun TelegramBotApiClient.tryStopPoll(requestBody: StopPollRequest): TelegramResponse = - executeRequest("stopPoll", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "stopPoll") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "stopPoll") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to delete a message, including service messages, with the following limitations: - A message can only be deleted if it was sent less than 48 hours ago. - Service messages about a supergroup, channel, or forum topic creation can't be deleted. - A dice message in a private chat can only be deleted if it was sent more than 24 hours ago. - Bots can delete outgoing messages in private chats, groups, and supergroups. - Bots can delete incoming messages in private chats. - Bots granted can_post_messages permissions can delete outgoing messages in channels. - If the bot is an administrator of a group, it can delete any message there. - If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there. Returns True on success. */ suspend fun TelegramBotApiClient.tryDeleteMessage(requestBody: DeleteMessageRequest): TelegramResponse = - executeRequest("deleteMessage", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "deleteMessage") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "deleteMessage") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned. */ suspend fun TelegramBotApiClient.trySendSticker(requestBody: SendStickerRequest): TelegramResponse = - executeRequest("sendSticker", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendSticker") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendSticker") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get a sticker set. On success, a StickerSet object is returned. */ suspend fun TelegramBotApiClient.tryGetStickerSet(requestBody: GetStickerSetRequest): TelegramResponse = - executeRequest("getStickerSet", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getStickerSet") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getStickerSet") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of Sticker objects. */ suspend fun TelegramBotApiClient.tryGetCustomEmojiStickers(requestBody: GetCustomEmojiStickersRequest): TelegramResponse> = - executeRequest("getCustomEmojiStickers", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getCustomEmojiStickers") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getCustomEmojiStickers") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to upload a file with a sticker for later use in the createNewStickerSet and addStickerToSet methods (the file can be used multiple times). Returns the uploaded File on success. */ suspend fun TelegramBotApiClient.tryUploadStickerFile(requestBody: UploadStickerFileRequest): TelegramResponse = - executeRequest("uploadStickerFile", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "uploadStickerFile") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "uploadStickerFile") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. Returns True on success. */ suspend fun TelegramBotApiClient.tryCreateNewStickerSet(requestBody: CreateNewStickerSetRequest): TelegramResponse = - executeRequest("createNewStickerSet", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "createNewStickerSet") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "createNewStickerSet") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to add a new sticker to a set created by the bot. The format of the added sticker must match the format of the other stickers in the set. Emoji sticker sets can have up to 200 stickers. Animated and video sticker sets can have up to 50 stickers. Static sticker sets can have up to 120 stickers. Returns True on success. */ suspend fun TelegramBotApiClient.tryAddStickerToSet(requestBody: AddStickerToSetRequest): TelegramResponse = - executeRequest("addStickerToSet", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "addStickerToSet") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "addStickerToSet") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success. */ suspend fun TelegramBotApiClient.trySetStickerPositionInSet(requestBody: SetStickerPositionInSetRequest): TelegramResponse = - executeRequest("setStickerPositionInSet", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setStickerPositionInSet") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setStickerPositionInSet") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to delete a sticker from a set created by the bot. Returns True on success. */ suspend fun TelegramBotApiClient.tryDeleteStickerFromSet(requestBody: DeleteStickerFromSetRequest): TelegramResponse = - executeRequest("deleteStickerFromSet", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "deleteStickerFromSet") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "deleteStickerFromSet") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to change the list of emoji assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success. */ suspend fun TelegramBotApiClient.trySetStickerEmojiList(requestBody: SetStickerEmojiListRequest): TelegramResponse = - executeRequest("setStickerEmojiList", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setStickerEmojiList") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setStickerEmojiList") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to change search keywords assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success. */ suspend fun TelegramBotApiClient.trySetStickerKeywords(requestBody: SetStickerKeywordsRequest): TelegramResponse = - executeRequest("setStickerKeywords", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setStickerKeywords") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setStickerKeywords") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to change the mask position of a mask sticker. The sticker must belong to a sticker set that was created by the bot. Returns True on success. */ suspend fun TelegramBotApiClient.trySetStickerMaskPosition(requestBody: SetStickerMaskPositionRequest): TelegramResponse = - executeRequest("setStickerMaskPosition", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setStickerMaskPosition") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setStickerMaskPosition") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to set the title of a created sticker set. Returns True on success. */ suspend fun TelegramBotApiClient.trySetStickerSetTitle(requestBody: SetStickerSetTitleRequest): TelegramResponse = - executeRequest("setStickerSetTitle", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setStickerSetTitle") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setStickerSetTitle") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to set the thumbnail of a regular or mask sticker set. The format of the thumbnail file must match the format of the stickers in the set. Returns True on success. */ suspend fun TelegramBotApiClient.trySetStickerSetThumbnail(requestBody: SetStickerSetThumbnailRequest): TelegramResponse = - executeRequest("setStickerSetThumbnail", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setStickerSetThumbnail") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setStickerSetThumbnail") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to set the thumbnail of a custom emoji sticker set. Returns True on success. */ suspend fun TelegramBotApiClient.trySetCustomEmojiStickerSetThumbnail(requestBody: SetCustomEmojiStickerSetThumbnailRequest): TelegramResponse = - executeRequest("setCustomEmojiStickerSetThumbnail", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setCustomEmojiStickerSetThumbnail") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setCustomEmojiStickerSetThumbnail") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to delete a sticker set that was created by the bot. Returns True on success. */ suspend fun TelegramBotApiClient.tryDeleteStickerSet(requestBody: DeleteStickerSetRequest): TelegramResponse = - executeRequest("deleteStickerSet", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "deleteStickerSet") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "deleteStickerSet") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send answers to an inline query. On success, True is returned. No more than 50 results per query are allowed. */ suspend fun TelegramBotApiClient.tryAnswerInlineQuery(requestBody: AnswerInlineQueryRequest): TelegramResponse = - executeRequest("answerInlineQuery", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "answerInlineQuery") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "answerInlineQuery") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned. */ suspend fun TelegramBotApiClient.tryAnswerWebAppQuery(requestBody: AnswerWebAppQueryRequest): TelegramResponse = - executeRequest("answerWebAppQuery", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "answerWebAppQuery") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "answerWebAppQuery") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send invoices. On success, the sent Message is returned. */ suspend fun TelegramBotApiClient.trySendInvoice(requestBody: SendInvoiceRequest): TelegramResponse = - executeRequest("sendInvoice", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendInvoice") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendInvoice") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to create a link for an invoice. Returns the created invoice link as String on success. */ suspend fun TelegramBotApiClient.tryCreateInvoiceLink(requestBody: CreateInvoiceLinkRequest): TelegramResponse = - executeRequest("createInvoiceLink", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "createInvoiceLink") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "createInvoiceLink") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. */ suspend fun TelegramBotApiClient.tryAnswerShippingQuery(requestBody: AnswerShippingQueryRequest): TelegramResponse = - executeRequest("answerShippingQuery", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "answerShippingQuery") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "answerShippingQuery") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. */ suspend fun TelegramBotApiClient.tryAnswerPreCheckoutQuery(requestBody: AnswerPreCheckoutQueryRequest): TelegramResponse = - executeRequest("answerPreCheckoutQuery", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "answerPreCheckoutQuery") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "answerPreCheckoutQuery") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success. @@ -1984,69 +1752,61 @@ suspend fun TelegramBotApiClient.tryAnswerPreCheckoutQuery(requestBody: AnswerPr * Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues. */ suspend fun TelegramBotApiClient.trySetPassportDataErrors(requestBody: SetPassportDataErrorsRequest): TelegramResponse = - executeRequest("setPassportDataErrors", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setPassportDataErrors") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setPassportDataErrors") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to send a game. On success, the sent Message is returned. */ suspend fun TelegramBotApiClient.trySendGame(requestBody: SendGameRequest): TelegramResponse = - executeRequest("sendGame", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "sendGame") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "sendGame") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to set the score of the specified user in a game message. On success the edited Message is returned. Returns an error, if the new score is not greater than the user's current score in the chat and force is False. */ suspend fun TelegramBotApiClient.trySetGameScore(requestBody: SetGameScoreRequest): TelegramResponse = - executeRequest("setGameScore", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setGameScore") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setGameScore") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to set the score of the specified user in a game message. On success True is returned. Returns an error, if the new score is not greater than the user's current score in the chat and force is False. */ suspend fun TelegramBotApiClient.trySetInlineGameScore(requestBody: SetGameScoreRequest): TelegramResponse = - executeRequest("setGameScore", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "setGameScore") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "setGameScore") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() /** * Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. Returns an Array of GameHighScore objects. @@ -2054,16 +1814,14 @@ suspend fun TelegramBotApiClient.trySetInlineGameScore(requestBody: SetGameScore * This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and their neighbors are not among them. Please note that this behavior is subject to change. */ suspend fun TelegramBotApiClient.tryGetGameHighScores(requestBody: GetGameHighScoresRequest): TelegramResponse> = - executeRequest("getGameHighScores", requestBody) { - httpClient.post { - url { - protocol = apiProtocol - host = apiHost - port = apiPort - path("bot$apiToken", "getGameHighScores") - } - contentType(ContentType.Application.Json) - setBody(requestBody) - }.body() - } + httpClient.post { + url { + protocol = apiProtocol + host = apiHost + port = apiPort + path("bot$apiToken", "getGameHighScores") + } + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() diff --git a/src/main/generated-kotlin/me/alllex/tbot/api/model/Types.kt b/src/main/generated-kotlin/me/alllex/tbot/api/model/Types.kt index 13282cd..4278c74 100644 --- a/src/main/generated-kotlin/me/alllex/tbot/api/model/Types.kt +++ b/src/main/generated-kotlin/me/alllex/tbot/api/model/Types.kt @@ -2,12 +2,14 @@ package me.alllex.tbot.api.model -import kotlinx.serialization.json.* import kotlinx.serialization.DeserializationStrategy import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.JsonClassDiscriminator +import kotlinx.serialization.json.JsonContentPolymorphicSerializer +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.jsonObject /** * Type of updates Telegram Bot can receive. @@ -49,9 +51,9 @@ enum class UpdateType { * - [ChatJoinRequestUpdate] */ @Serializable(with = UpdateSerializer::class) -sealed class Update { - abstract val updateId: Long - abstract val updateType: UpdateType +sealed interface Update { + val updateId: Long + val updateType: UpdateType } /** @@ -61,7 +63,7 @@ sealed class Update { data class MessageUpdate( override val updateId: Long, val message: Message, -): Update() { +): Update { override val updateType: UpdateType get() = UpdateType.MESSAGE } @@ -72,7 +74,7 @@ data class MessageUpdate( data class EditedMessageUpdate( override val updateId: Long, val editedMessage: Message, -): Update() { +): Update { override val updateType: UpdateType get() = UpdateType.EDITED_MESSAGE } @@ -83,7 +85,7 @@ data class EditedMessageUpdate( data class ChannelPostUpdate( override val updateId: Long, val channelPost: Message, -): Update() { +): Update { override val updateType: UpdateType get() = UpdateType.CHANNEL_POST } @@ -94,7 +96,7 @@ data class ChannelPostUpdate( data class EditedChannelPostUpdate( override val updateId: Long, val editedChannelPost: Message, -): Update() { +): Update { override val updateType: UpdateType get() = UpdateType.EDITED_CHANNEL_POST } @@ -105,7 +107,7 @@ data class EditedChannelPostUpdate( data class InlineQueryUpdate( override val updateId: Long, val inlineQuery: InlineQuery, -): Update() { +): Update { override val updateType: UpdateType get() = UpdateType.INLINE_QUERY } @@ -116,7 +118,7 @@ data class InlineQueryUpdate( data class ChosenInlineResultUpdate( override val updateId: Long, val chosenInlineResult: ChosenInlineResult, -): Update() { +): Update { override val updateType: UpdateType get() = UpdateType.CHOSEN_INLINE_RESULT } @@ -127,7 +129,7 @@ data class ChosenInlineResultUpdate( data class CallbackQueryUpdate( override val updateId: Long, val callbackQuery: CallbackQuery, -): Update() { +): Update { override val updateType: UpdateType get() = UpdateType.CALLBACK_QUERY } @@ -138,7 +140,7 @@ data class CallbackQueryUpdate( data class ShippingQueryUpdate( override val updateId: Long, val shippingQuery: ShippingQuery, -): Update() { +): Update { override val updateType: UpdateType get() = UpdateType.SHIPPING_QUERY } @@ -149,7 +151,7 @@ data class ShippingQueryUpdate( data class PreCheckoutQueryUpdate( override val updateId: Long, val preCheckoutQuery: PreCheckoutQuery, -): Update() { +): Update { override val updateType: UpdateType get() = UpdateType.PRE_CHECKOUT_QUERY } @@ -160,7 +162,7 @@ data class PreCheckoutQueryUpdate( data class PollUpdate( override val updateId: Long, val poll: Poll, -): Update() { +): Update { override val updateType: UpdateType get() = UpdateType.POLL } @@ -171,7 +173,7 @@ data class PollUpdate( data class PollAnswerUpdate( override val updateId: Long, val pollAnswer: PollAnswer, -): Update() { +): Update { override val updateType: UpdateType get() = UpdateType.POLL_ANSWER } @@ -182,7 +184,7 @@ data class PollAnswerUpdate( data class MyChatMemberUpdate( override val updateId: Long, val myChatMember: ChatMemberUpdated, -): Update() { +): Update { override val updateType: UpdateType get() = UpdateType.MY_CHAT_MEMBER } @@ -193,7 +195,7 @@ data class MyChatMemberUpdate( data class ChatMemberUpdate( override val updateId: Long, val chatMember: ChatMemberUpdated, -): Update() { +): Update { override val updateType: UpdateType get() = UpdateType.CHAT_MEMBER } @@ -204,7 +206,7 @@ data class ChatMemberUpdate( data class ChatJoinRequestUpdate( override val updateId: Long, val chatJoinRequest: ChatJoinRequest, -): Update() { +): Update { override val updateType: UpdateType get() = UpdateType.CHAT_JOIN_REQUEST } @@ -1081,7 +1083,7 @@ data class ReplyKeyboardMarkup( val oneTimeKeyboard: Boolean? = null, val inputFieldPlaceholder: String? = null, val selective: Boolean? = null, -) : ReplyMarkup() { +) : ReplyMarkup { override fun toString() = DebugStringBuilder("ReplyKeyboardMarkup").prop("keyboard", keyboard).prop("isPersistent", isPersistent).prop("resizeKeyboard", resizeKeyboard).prop("oneTimeKeyboard", oneTimeKeyboard).prop("inputFieldPlaceholder", inputFieldPlaceholder).prop("selective", selective).toString() } @@ -1168,7 +1170,7 @@ data class KeyboardButtonPollType( data class ReplyKeyboardRemove( val removeKeyboard: Boolean, val selective: Boolean? = null, -) : ReplyMarkup() { +) : ReplyMarkup { override fun toString() = DebugStringBuilder("ReplyKeyboardRemove").prop("removeKeyboard", removeKeyboard).prop("selective", selective).toString() } @@ -1179,7 +1181,7 @@ data class ReplyKeyboardRemove( @Serializable data class InlineKeyboardMarkup( val inlineKeyboard: List>, -) : ReplyMarkup() { +) : ReplyMarkup { override fun toString() = DebugStringBuilder("InlineKeyboardMarkup").prop("inlineKeyboard", inlineKeyboard).toString() } @@ -1286,7 +1288,7 @@ data class ForceReply( val forceReply: Boolean, val inputFieldPlaceholder: String? = null, val selective: Boolean? = null, -) : ReplyMarkup() { +) : ReplyMarkup { override fun toString() = DebugStringBuilder("ForceReply").prop("forceReply", forceReply).prop("inputFieldPlaceholder", inputFieldPlaceholder).prop("selective", selective).toString() } @@ -1384,7 +1386,7 @@ data class ChatAdministratorRights( */ @Serializable @JsonClassDiscriminator("status") -sealed class ChatMember +sealed interface ChatMember /** * Represents a chat member that owns the chat and has all administrator privileges. @@ -1398,7 +1400,7 @@ data class ChatMemberOwner( val user: User, val isAnonymous: Boolean, val customTitle: String? = null, -) : ChatMember() { +) : ChatMember { override fun toString() = DebugStringBuilder("ChatMemberOwner").prop("user", user).prop("isAnonymous", isAnonymous).prop("customTitle", customTitle).toString() } @@ -1444,7 +1446,7 @@ data class ChatMemberAdministrator( val canDeleteStories: Boolean? = null, val canManageTopics: Boolean? = null, val customTitle: String? = null, -) : ChatMember() { +) : ChatMember { override fun toString() = DebugStringBuilder("ChatMemberAdministrator").prop("user", user).prop("canBeEdited", canBeEdited).prop("isAnonymous", isAnonymous).prop("canManageChat", canManageChat).prop("canDeleteMessages", canDeleteMessages).prop("canManageVideoChats", canManageVideoChats).prop("canRestrictMembers", canRestrictMembers).prop("canPromoteMembers", canPromoteMembers).prop("canChangeInfo", canChangeInfo).prop("canInviteUsers", canInviteUsers).prop("canPostMessages", canPostMessages).prop("canEditMessages", canEditMessages).prop("canPinMessages", canPinMessages).prop("canPostStories", canPostStories).prop("canEditStories", canEditStories).prop("canDeleteStories", canDeleteStories).prop("canManageTopics", canManageTopics).prop("customTitle", customTitle).toString() } @@ -1456,7 +1458,7 @@ data class ChatMemberAdministrator( @SerialName("member") data class ChatMemberMember( val user: User, -) : ChatMember() { +) : ChatMember { override fun toString() = DebugStringBuilder("ChatMemberMember").prop("user", user).toString() } @@ -1500,7 +1502,7 @@ data class ChatMemberRestricted( val canPinMessages: Boolean, val canManageTopics: Boolean, val untilDate: UnixTimestamp, -) : ChatMember() { +) : ChatMember { override fun toString() = DebugStringBuilder("ChatMemberRestricted").prop("user", user).prop("isMember", isMember).prop("canSendMessages", canSendMessages).prop("canSendAudios", canSendAudios).prop("canSendDocuments", canSendDocuments).prop("canSendPhotos", canSendPhotos).prop("canSendVideos", canSendVideos).prop("canSendVideoNotes", canSendVideoNotes).prop("canSendVoiceNotes", canSendVoiceNotes).prop("canSendPolls", canSendPolls).prop("canSendOtherMessages", canSendOtherMessages).prop("canAddWebPagePreviews", canAddWebPagePreviews).prop("canChangeInfo", canChangeInfo).prop("canInviteUsers", canInviteUsers).prop("canPinMessages", canPinMessages).prop("canManageTopics", canManageTopics).prop("untilDate", untilDate).toString() } @@ -1512,7 +1514,7 @@ data class ChatMemberRestricted( @SerialName("left") data class ChatMemberLeft( val user: User, -) : ChatMember() { +) : ChatMember { override fun toString() = DebugStringBuilder("ChatMemberLeft").prop("user", user).toString() } @@ -1526,7 +1528,7 @@ data class ChatMemberLeft( data class ChatMemberBanned( val user: User, val untilDate: UnixTimestamp, -) : ChatMember() { +) : ChatMember { override fun toString() = DebugStringBuilder("ChatMemberBanned").prop("user", user).prop("untilDate", untilDate).toString() } @@ -1666,35 +1668,35 @@ data class BotCommand( */ @Serializable @JsonClassDiscriminator("type") -sealed class BotCommandScope +sealed interface BotCommandScope /** * Represents the default scope of bot commands. Default commands are used if no commands with a narrower scope are specified for the user. */ @Serializable @SerialName("default") -data object BotCommandScopeDefault : BotCommandScope() +data object BotCommandScopeDefault : BotCommandScope /** * Represents the scope of bot commands, covering all private chats. */ @Serializable @SerialName("all_private_chats") -data object BotCommandScopeAllPrivateChats : BotCommandScope() +data object BotCommandScopeAllPrivateChats : BotCommandScope /** * Represents the scope of bot commands, covering all group and supergroup chats. */ @Serializable @SerialName("all_group_chats") -data object BotCommandScopeAllGroupChats : BotCommandScope() +data object BotCommandScopeAllGroupChats : BotCommandScope /** * Represents the scope of bot commands, covering all group and supergroup chat administrators. */ @Serializable @SerialName("all_chat_administrators") -data object BotCommandScopeAllChatAdministrators : BotCommandScope() +data object BotCommandScopeAllChatAdministrators : BotCommandScope /** * Represents the scope of bot commands, covering a specific chat. @@ -1704,7 +1706,7 @@ data object BotCommandScopeAllChatAdministrators : BotCommandScope() @SerialName("chat") data class BotCommandScopeChat( val chatId: ChatId, -) : BotCommandScope() { +) : BotCommandScope { override fun toString() = DebugStringBuilder("BotCommandScopeChat").prop("chatId", chatId).toString() } @@ -1716,7 +1718,7 @@ data class BotCommandScopeChat( @SerialName("chat_administrators") data class BotCommandScopeChatAdministrators( val chatId: ChatId, -) : BotCommandScope() { +) : BotCommandScope { override fun toString() = DebugStringBuilder("BotCommandScopeChatAdministrators").prop("chatId", chatId).toString() } @@ -1730,7 +1732,7 @@ data class BotCommandScopeChatAdministrators( data class BotCommandScopeChatMember( val chatId: ChatId, val userId: UserId, -) : BotCommandScope() { +) : BotCommandScope { override fun toString() = DebugStringBuilder("BotCommandScopeChatMember").prop("chatId", chatId).prop("userId", userId).toString() } @@ -1775,14 +1777,14 @@ data class BotShortDescription( */ @Serializable @JsonClassDiscriminator("type") -sealed class MenuButton +sealed interface MenuButton /** * Represents a menu button, which opens the bot's list of commands. */ @Serializable @SerialName("commands") -data object MenuButtonCommands : MenuButton() +data object MenuButtonCommands : MenuButton /** * Represents a menu button, which launches a Web App. @@ -1794,7 +1796,7 @@ data object MenuButtonCommands : MenuButton() data class MenuButtonWebApp( val text: String, val webApp: WebAppInfo, -) : MenuButton() { +) : MenuButton { override fun toString() = DebugStringBuilder("MenuButtonWebApp").prop("text", text).prop("webApp", webApp).toString() } @@ -1803,7 +1805,7 @@ data class MenuButtonWebApp( */ @Serializable @SerialName("default") -data object MenuButtonDefault : MenuButton() +data object MenuButtonDefault : MenuButton /** * Describes why a request was unsuccessful. @@ -1828,7 +1830,7 @@ data class ResponseParameters( */ @Serializable @JsonClassDiscriminator("type") -sealed class InputMedia +sealed interface InputMedia /** * Represents a photo to be sent. @@ -1846,7 +1848,7 @@ data class InputMediaPhoto( val parseMode: ParseMode? = null, val captionEntities: List? = null, val hasSpoiler: Boolean? = null, -) : InputMedia() { +) : InputMedia { override fun toString() = DebugStringBuilder("InputMediaPhoto").prop("media", media).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("hasSpoiler", hasSpoiler).toString() } @@ -1876,7 +1878,7 @@ data class InputMediaVideo( val duration: Seconds? = null, val supportsStreaming: Boolean? = null, val hasSpoiler: Boolean? = null, -) : InputMedia() { +) : InputMedia { override fun toString() = DebugStringBuilder("InputMediaVideo").prop("media", media).prop("thumbnail", thumbnail).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("width", width).prop("height", height).prop("duration", duration).prop("supportsStreaming", supportsStreaming).prop("hasSpoiler", hasSpoiler).toString() } @@ -1904,7 +1906,7 @@ data class InputMediaAnimation( val height: Long? = null, val duration: Seconds? = null, val hasSpoiler: Boolean? = null, -) : InputMedia() { +) : InputMedia { override fun toString() = DebugStringBuilder("InputMediaAnimation").prop("media", media).prop("thumbnail", thumbnail).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("width", width).prop("height", height).prop("duration", duration).prop("hasSpoiler", hasSpoiler).toString() } @@ -1930,7 +1932,7 @@ data class InputMediaAudio( val duration: Seconds? = null, val performer: String? = null, val title: String? = null, -) : InputMedia() { +) : InputMedia { override fun toString() = DebugStringBuilder("InputMediaAudio").prop("media", media).prop("thumbnail", thumbnail).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("duration", duration).prop("performer", performer).prop("title", title).toString() } @@ -1952,7 +1954,7 @@ data class InputMediaDocument( val parseMode: ParseMode? = null, val captionEntities: List? = null, val disableContentTypeDetection: Boolean? = null, -) : InputMedia() { +) : InputMedia { override fun toString() = DebugStringBuilder("InputMediaDocument").prop("media", media).prop("thumbnail", thumbnail).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("disableContentTypeDetection", disableContentTypeDetection).toString() } @@ -2113,7 +2115,7 @@ data class InlineQueryResultsButton( */ @Serializable @JsonClassDiscriminator("type") -sealed class InlineQueryResult +sealed interface InlineQueryResult /** * Represents a link to an article or web page. @@ -2141,7 +2143,7 @@ data class InlineQueryResultArticle( val thumbnailUrl: String? = null, val thumbnailWidth: Long? = null, val thumbnailHeight: Long? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultArticle").prop("id", id).prop("title", title).prop("inputMessageContent", inputMessageContent).prop("replyMarkup", replyMarkup).prop("url", url).prop("hideUrl", hideUrl).prop("description", description).prop("thumbnailUrl", thumbnailUrl).prop("thumbnailWidth", thumbnailWidth).prop("thumbnailHeight", thumbnailHeight).toString() } @@ -2175,7 +2177,7 @@ data class InlineQueryResultPhoto( val captionEntities: List? = null, val replyMarkup: InlineKeyboardMarkup? = null, val inputMessageContent: InputMessageContent? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultPhoto").prop("id", id).prop("photoUrl", photoUrl).prop("thumbnailUrl", thumbnailUrl).prop("photoWidth", photoWidth).prop("photoHeight", photoHeight).prop("title", title).prop("description", description).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).toString() } @@ -2211,7 +2213,7 @@ data class InlineQueryResultGif( val captionEntities: List? = null, val replyMarkup: InlineKeyboardMarkup? = null, val inputMessageContent: InputMessageContent? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultGif").prop("id", id).prop("gifUrl", gifUrl).prop("thumbnailUrl", thumbnailUrl).prop("gifWidth", gifWidth).prop("gifHeight", gifHeight).prop("gifDuration", gifDuration).prop("thumbnailMimeType", thumbnailMimeType).prop("title", title).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).toString() } @@ -2247,7 +2249,7 @@ data class InlineQueryResultMpeg4Gif( val captionEntities: List? = null, val replyMarkup: InlineKeyboardMarkup? = null, val inputMessageContent: InputMessageContent? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultMpeg4Gif").prop("id", id).prop("mpeg4Url", mpeg4Url).prop("thumbnailUrl", thumbnailUrl).prop("mpeg4Width", mpeg4Width).prop("mpeg4Height", mpeg4Height).prop("mpeg4Duration", mpeg4Duration).prop("thumbnailMimeType", thumbnailMimeType).prop("title", title).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).toString() } @@ -2287,7 +2289,7 @@ data class InlineQueryResultVideo( val description: String? = null, val replyMarkup: InlineKeyboardMarkup? = null, val inputMessageContent: InputMessageContent? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultVideo").prop("id", id).prop("videoUrl", videoUrl).prop("mimeType", mimeType).prop("thumbnailUrl", thumbnailUrl).prop("title", title).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("videoWidth", videoWidth).prop("videoHeight", videoHeight).prop("videoDuration", videoDuration).prop("description", description).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).toString() } @@ -2317,7 +2319,7 @@ data class InlineQueryResultAudio( val audioDuration: Long? = null, val replyMarkup: InlineKeyboardMarkup? = null, val inputMessageContent: InputMessageContent? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultAudio").prop("id", id).prop("audioUrl", audioUrl).prop("title", title).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("performer", performer).prop("audioDuration", audioDuration).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).toString() } @@ -2345,7 +2347,7 @@ data class InlineQueryResultVoice( val voiceDuration: Long? = null, val replyMarkup: InlineKeyboardMarkup? = null, val inputMessageContent: InputMessageContent? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultVoice").prop("id", id).prop("voiceUrl", voiceUrl).prop("title", title).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("voiceDuration", voiceDuration).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).toString() } @@ -2381,7 +2383,7 @@ data class InlineQueryResultDocument( val thumbnailUrl: String? = null, val thumbnailWidth: Long? = null, val thumbnailHeight: Long? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultDocument").prop("id", id).prop("title", title).prop("documentUrl", documentUrl).prop("mimeType", mimeType).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("description", description).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).prop("thumbnailUrl", thumbnailUrl).prop("thumbnailWidth", thumbnailWidth).prop("thumbnailHeight", thumbnailHeight).toString() } @@ -2417,7 +2419,7 @@ data class InlineQueryResultLocation( val thumbnailUrl: String? = null, val thumbnailWidth: Long? = null, val thumbnailHeight: Long? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultLocation").prop("id", id).prop("latitude", latitude).prop("longitude", longitude).prop("title", title).prop("horizontalAccuracy", horizontalAccuracy).prop("livePeriod", livePeriod).prop("heading", heading).prop("proximityAlertRadius", proximityAlertRadius).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).prop("thumbnailUrl", thumbnailUrl).prop("thumbnailWidth", thumbnailWidth).prop("thumbnailHeight", thumbnailHeight).toString() } @@ -2455,7 +2457,7 @@ data class InlineQueryResultVenue( val thumbnailUrl: String? = null, val thumbnailWidth: Long? = null, val thumbnailHeight: Long? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultVenue").prop("id", id).prop("latitude", latitude).prop("longitude", longitude).prop("title", title).prop("address", address).prop("foursquareId", foursquareId).prop("foursquareType", foursquareType).prop("googlePlaceId", googlePlaceId).prop("googlePlaceType", googlePlaceType).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).prop("thumbnailUrl", thumbnailUrl).prop("thumbnailWidth", thumbnailWidth).prop("thumbnailHeight", thumbnailHeight).toString() } @@ -2485,7 +2487,7 @@ data class InlineQueryResultContact( val thumbnailUrl: String? = null, val thumbnailWidth: Long? = null, val thumbnailHeight: Long? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultContact").prop("id", id).prop("phoneNumber", phoneNumber).prop("firstName", firstName).prop("lastName", lastName).prop("vcard", vcard).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).prop("thumbnailUrl", thumbnailUrl).prop("thumbnailWidth", thumbnailWidth).prop("thumbnailHeight", thumbnailHeight).toString() } @@ -2501,7 +2503,7 @@ data class InlineQueryResultGame( val id: InlineQueryResultId, val gameShortName: String, val replyMarkup: InlineKeyboardMarkup? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultGame").prop("id", id).prop("gameShortName", gameShortName).prop("replyMarkup", replyMarkup).toString() } @@ -2529,7 +2531,7 @@ data class InlineQueryResultCachedPhoto( val captionEntities: List? = null, val replyMarkup: InlineKeyboardMarkup? = null, val inputMessageContent: InputMessageContent? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultCachedPhoto").prop("id", id).prop("photoFileId", photoFileId).prop("title", title).prop("description", description).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).toString() } @@ -2555,7 +2557,7 @@ data class InlineQueryResultCachedGif( val captionEntities: List? = null, val replyMarkup: InlineKeyboardMarkup? = null, val inputMessageContent: InputMessageContent? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultCachedGif").prop("id", id).prop("gifFileId", gifFileId).prop("title", title).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).toString() } @@ -2581,7 +2583,7 @@ data class InlineQueryResultCachedMpeg4Gif( val captionEntities: List? = null, val replyMarkup: InlineKeyboardMarkup? = null, val inputMessageContent: InputMessageContent? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultCachedMpeg4Gif").prop("id", id).prop("mpeg4FileId", mpeg4FileId).prop("title", title).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).toString() } @@ -2599,7 +2601,7 @@ data class InlineQueryResultCachedSticker( val stickerFileId: FileId, val replyMarkup: InlineKeyboardMarkup? = null, val inputMessageContent: InputMessageContent? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultCachedSticker").prop("id", id).prop("stickerFileId", stickerFileId).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).toString() } @@ -2627,7 +2629,7 @@ data class InlineQueryResultCachedDocument( val captionEntities: List? = null, val replyMarkup: InlineKeyboardMarkup? = null, val inputMessageContent: InputMessageContent? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultCachedDocument").prop("id", id).prop("title", title).prop("documentFileId", documentFileId).prop("description", description).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).toString() } @@ -2655,7 +2657,7 @@ data class InlineQueryResultCachedVideo( val captionEntities: List? = null, val replyMarkup: InlineKeyboardMarkup? = null, val inputMessageContent: InputMessageContent? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultCachedVideo").prop("id", id).prop("videoFileId", videoFileId).prop("title", title).prop("description", description).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).toString() } @@ -2681,7 +2683,7 @@ data class InlineQueryResultCachedVoice( val captionEntities: List? = null, val replyMarkup: InlineKeyboardMarkup? = null, val inputMessageContent: InputMessageContent? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultCachedVoice").prop("id", id).prop("voiceFileId", voiceFileId).prop("title", title).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).toString() } @@ -2705,7 +2707,7 @@ data class InlineQueryResultCachedAudio( val captionEntities: List? = null, val replyMarkup: InlineKeyboardMarkup? = null, val inputMessageContent: InputMessageContent? = null, -) : InlineQueryResult() { +) : InlineQueryResult { override fun toString() = DebugStringBuilder("InlineQueryResultCachedAudio").prop("id", id).prop("audioFileId", audioFileId).prop("caption", caption).prop("parseMode", parseMode).prop("captionEntities", captionEntities).prop("replyMarkup", replyMarkup).prop("inputMessageContent", inputMessageContent).toString() } @@ -2718,7 +2720,7 @@ data class InlineQueryResultCachedAudio( * - [InputInvoiceMessageContent] */ @Serializable(with = InputMessageContentSerializer::class) -sealed class InputMessageContent +sealed interface InputMessageContent object InputMessageContentSerializer : JsonContentPolymorphicSerializer(InputMessageContent::class) { override fun selectDeserializer(element: JsonElement): DeserializationStrategy { @@ -2747,7 +2749,7 @@ data class InputTextMessageContent( val parseMode: ParseMode? = null, val entities: List? = null, val disableWebPagePreview: Boolean? = null, -) : InputMessageContent() { +) : InputMessageContent { override fun toString() = DebugStringBuilder("InputTextMessageContent").prop("messageText", messageText).prop("parseMode", parseMode).prop("entities", entities).prop("disableWebPagePreview", disableWebPagePreview).toString() } @@ -2768,7 +2770,7 @@ data class InputLocationMessageContent( val livePeriod: Long? = null, val heading: Long? = null, val proximityAlertRadius: Long? = null, -) : InputMessageContent() { +) : InputMessageContent { override fun toString() = DebugStringBuilder("InputLocationMessageContent").prop("latitude", latitude).prop("longitude", longitude).prop("horizontalAccuracy", horizontalAccuracy).prop("livePeriod", livePeriod).prop("heading", heading).prop("proximityAlertRadius", proximityAlertRadius).toString() } @@ -2793,7 +2795,7 @@ data class InputVenueMessageContent( val foursquareType: String? = null, val googlePlaceId: String? = null, val googlePlaceType: String? = null, -) : InputMessageContent() { +) : InputMessageContent { override fun toString() = DebugStringBuilder("InputVenueMessageContent").prop("latitude", latitude).prop("longitude", longitude).prop("title", title).prop("address", address).prop("foursquareId", foursquareId).prop("foursquareType", foursquareType).prop("googlePlaceId", googlePlaceId).prop("googlePlaceType", googlePlaceType).toString() } @@ -2810,7 +2812,7 @@ data class InputContactMessageContent( val firstName: String, val lastName: String? = null, val vcard: String? = null, -) : InputMessageContent() { +) : InputMessageContent { override fun toString() = DebugStringBuilder("InputContactMessageContent").prop("phoneNumber", phoneNumber).prop("firstName", firstName).prop("lastName", lastName).prop("vcard", vcard).toString() } @@ -2859,7 +2861,7 @@ data class InputInvoiceMessageContent( val sendPhoneNumberToProvider: Boolean? = null, val sendEmailToProvider: Boolean? = null, val isFlexible: Boolean? = null, -) : InputMessageContent() { +) : InputMessageContent { override fun toString() = DebugStringBuilder("InputInvoiceMessageContent").prop("title", title).prop("description", description).prop("payload", payload).prop("providerToken", providerToken).prop("currency", currency).prop("prices", prices).prop("maxTipAmount", maxTipAmount).prop("suggestedTipAmounts", suggestedTipAmounts).prop("providerData", providerData).prop("photoUrl", photoUrl).prop("photoSize", photoSize).prop("photoWidth", photoWidth).prop("photoHeight", photoHeight).prop("needName", needName).prop("needPhoneNumber", needPhoneNumber).prop("needEmail", needEmail).prop("needShippingAddress", needShippingAddress).prop("sendPhoneNumberToProvider", sendPhoneNumberToProvider).prop("sendEmailToProvider", sendEmailToProvider).prop("isFlexible", isFlexible).toString() } @@ -3129,7 +3131,7 @@ data class EncryptedCredentials( */ @Serializable @JsonClassDiscriminator("type") -sealed class PassportElementError +sealed interface PassportElementError /** * Represents an issue in one of the data fields that was provided by the user. The error is considered resolved when the field's value changes. @@ -3146,7 +3148,7 @@ data class PassportElementErrorDataField( val fieldName: String, val dataHash: String, val message: String, -) : PassportElementError() { +) : PassportElementError { override fun toString() = DebugStringBuilder("PassportElementErrorDataField").prop("source", source).prop("type", type).prop("fieldName", fieldName).prop("dataHash", dataHash).prop("message", message).toString() } @@ -3163,7 +3165,7 @@ data class PassportElementErrorFrontSide( val type: String, val fileHash: String, val message: String, -) : PassportElementError() { +) : PassportElementError { override fun toString() = DebugStringBuilder("PassportElementErrorFrontSide").prop("source", source).prop("type", type).prop("fileHash", fileHash).prop("message", message).toString() } @@ -3180,7 +3182,7 @@ data class PassportElementErrorReverseSide( val type: String, val fileHash: String, val message: String, -) : PassportElementError() { +) : PassportElementError { override fun toString() = DebugStringBuilder("PassportElementErrorReverseSide").prop("source", source).prop("type", type).prop("fileHash", fileHash).prop("message", message).toString() } @@ -3197,7 +3199,7 @@ data class PassportElementErrorSelfie( val type: String, val fileHash: String, val message: String, -) : PassportElementError() { +) : PassportElementError { override fun toString() = DebugStringBuilder("PassportElementErrorSelfie").prop("source", source).prop("type", type).prop("fileHash", fileHash).prop("message", message).toString() } @@ -3214,7 +3216,7 @@ data class PassportElementErrorFile( val type: String, val fileHash: String, val message: String, -) : PassportElementError() { +) : PassportElementError { override fun toString() = DebugStringBuilder("PassportElementErrorFile").prop("source", source).prop("type", type).prop("fileHash", fileHash).prop("message", message).toString() } @@ -3231,7 +3233,7 @@ data class PassportElementErrorFiles( val type: String, val fileHashes: List, val message: String, -) : PassportElementError() { +) : PassportElementError { override fun toString() = DebugStringBuilder("PassportElementErrorFiles").prop("source", source).prop("type", type).prop("fileHashes", fileHashes).prop("message", message).toString() } @@ -3248,7 +3250,7 @@ data class PassportElementErrorTranslationFile( val type: String, val fileHash: String, val message: String, -) : PassportElementError() { +) : PassportElementError { override fun toString() = DebugStringBuilder("PassportElementErrorTranslationFile").prop("source", source).prop("type", type).prop("fileHash", fileHash).prop("message", message).toString() } @@ -3265,7 +3267,7 @@ data class PassportElementErrorTranslationFiles( val type: String, val fileHashes: List, val message: String, -) : PassportElementError() { +) : PassportElementError { override fun toString() = DebugStringBuilder("PassportElementErrorTranslationFiles").prop("source", source).prop("type", type).prop("fileHashes", fileHashes).prop("message", message).toString() } @@ -3282,7 +3284,7 @@ data class PassportElementErrorUnspecified( val type: String, val elementHash: String, val message: String, -) : PassportElementError() { +) : PassportElementError { override fun toString() = DebugStringBuilder("PassportElementErrorUnspecified").prop("source", source).prop("type", type).prop("elementHash", elementHash).prop("message", message).toString() } @@ -3336,7 +3338,7 @@ data class GameHighScore( * - [ForceReply] */ @Serializable(with = ReplyMarkupSerializer::class) -sealed class ReplyMarkup +sealed interface ReplyMarkup object ReplyMarkupSerializer : JsonContentPolymorphicSerializer(ReplyMarkup::class) { override fun selectDeserializer(element: JsonElement): DeserializationStrategy { diff --git a/src/main/kotlin/me/alllex/tbot/api/client/TelegramBotApiClient.kt b/src/main/kotlin/me/alllex/tbot/api/client/TelegramBotApiClient.kt index 198edc7..d733f81 100644 --- a/src/main/kotlin/me/alllex/tbot/api/client/TelegramBotApiClient.kt +++ b/src/main/kotlin/me/alllex/tbot/api/client/TelegramBotApiClient.kt @@ -1,95 +1,75 @@ package me.alllex.tbot.api.client -import io.ktor.client.* -import io.ktor.client.engine.* -import io.ktor.client.plugins.contentnegotiation.* -import io.ktor.http.* -import io.ktor.serialization.kotlinx.json.* -import kotlinx.serialization.ExperimentalSerializationApi +import io.ktor.client.HttpClient +import io.ktor.client.HttpClientConfig +import io.ktor.client.engine.HttpClientEngine +import io.ktor.client.engine.HttpClientEngineConfig +import io.ktor.client.engine.HttpClientEngineFactory +import io.ktor.client.plugins.HttpRequestRetry +import io.ktor.client.plugins.HttpTimeout +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.http.DEFAULT_PORT +import io.ktor.http.URLProtocol +import io.ktor.serialization.kotlinx.json.json import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonNamingStrategy +import kotlin.time.Duration.Companion.seconds const val DEFAULT_TELEGRAM_API_HOST = "api.telegram.org" -class TelegramBotApiClient private constructor( - internal val httpClient: HttpClient, - internal val apiToken: String, - internal val apiProtocol: URLProtocol = URLProtocol.HTTPS, - internal val apiHost: String = DEFAULT_TELEGRAM_API_HOST, - internal val apiPort: Int = DEFAULT_PORT, - private val onRequest: (TelegramBotApiClient.(requestMethod: String, requestBody: Any?) -> Unit)? = null, - private val onResponse: (TelegramBotApiClient.(requestMethod: String, requestBody: Any?, responseBody: TelegramResponse<*>) -> Unit)? = null, +class TelegramBotApiClient( + val apiToken: String, + val httpClient: HttpClient = httpClient(), + val apiProtocol: URLProtocol = URLProtocol.HTTPS, + val apiHost: String = DEFAULT_TELEGRAM_API_HOST, + val apiPort: Int = DEFAULT_PORT, ) { - internal inline fun executeRequest(requestMethod: String, requestBody: Any?, request: () -> TelegramResponse): TelegramResponse { - onRequest?.invoke(this, requestMethod, requestBody) - val responseBody = request() - onResponse?.invoke(this, requestMethod, requestBody, responseBody) - return responseBody - } - - fun closeHttpClient() { - httpClient.close() - } + companion object Defaults { - companion object { + val JSON + get() = Json { + // chat_id to chatId + namingStrategy = JsonNamingStrategy.SnakeCase + // To avoid the deserialization breaking when Telegram introduces new fields + ignoreUnknownKeys = true + // Smaller payloads + explicitNulls = false + } - @OptIn(ExperimentalSerializationApi::class) - private fun HttpClientConfig<*>.applyDefaultConfiguration() { + fun HttpClientConfig<*>.defaultConfiguration() { install(ContentNegotiation) { - json(Json { - // chat_id to chatId - namingStrategy = JsonNamingStrategy.SnakeCase - // To avoid the deserialization breaking when Telegram introduces new fields - ignoreUnknownKeys = true - // Smaller payloads - explicitNulls = false - }) + json(JSON) + } + install(HttpTimeout) { + requestTimeout = 10.seconds + } + install(HttpRequestRetry) { + constantDelay() } } - operator fun invoke( - apiToken: String, - protocol: URLProtocol = URLProtocol.HTTPS, - engine: HttpClientEngine? = null, - host: String = DEFAULT_TELEGRAM_API_HOST, - port: Int = DEFAULT_PORT, - onRequest: (TelegramBotApiClient.(requestMethod: String, requestBody: Any?) -> Unit)? = null, - onResponse: (TelegramBotApiClient.(requestMethod: String, requestBody: Any?, responseBody: TelegramResponse<*>) -> Unit)? = null, - configuration: (HttpClientConfig<*>.() -> Unit)? = null, - ): TelegramBotApiClient { - val httpClient = if (engine == null) { - HttpClient { - applyDefaultConfiguration() - configuration?.invoke(this) - } - } else { - HttpClient(engine) { - applyDefaultConfiguration() - configuration?.invoke(this) - } - } - return TelegramBotApiClient(httpClient, apiToken, protocol, host, port, onRequest, onResponse) + fun httpClient(config: HttpClientConfig<*>.() -> Unit = {}) = HttpClient { + defaultConfiguration() + config() } - operator fun invoke( - apiToken: String, - engine: HttpClientEngineFactory, - protocol: URLProtocol = URLProtocol.HTTPS, - host: String = DEFAULT_TELEGRAM_API_HOST, - port: Int = DEFAULT_PORT, - onRequest: (TelegramBotApiClient.(requestMethod: String, requestBody: Any?) -> Unit)? = null, - onResponse: (TelegramBotApiClient.(requestMethod: String, requestBody: Any?, responseBody: TelegramResponse<*>) -> Unit)? = null, - configuration: (HttpClientConfig.() -> Unit)? = null, - ): TelegramBotApiClient { - val httpClient = HttpClient(engine) { - applyDefaultConfiguration() - configuration?.let { it() } - } - return TelegramBotApiClient(httpClient, apiToken, protocol, host, port, onRequest, onResponse) + fun httpClient( + engineFactory: HttpClientEngineFactory, + config: HttpClientConfig.() -> Unit = {} + ) = HttpClient(engineFactory) { + defaultConfiguration() + config() } + fun httpClient( + engine: HttpClientEngine, + config: HttpClientConfig<*>.() -> Unit = {} + ) = HttpClient(engine) { + defaultConfiguration() + config() + } } } diff --git a/src/main/kotlin/me/alllex/tbot/api/client/TelegramBotApiContext.kt b/src/main/kotlin/me/alllex/tbot/api/client/TelegramBotApiContext.kt index 04a66d9..c1563d1 100644 --- a/src/main/kotlin/me/alllex/tbot/api/client/TelegramBotApiContext.kt +++ b/src/main/kotlin/me/alllex/tbot/api/client/TelegramBotApiContext.kt @@ -1,5 +1,16 @@ package me.alllex.tbot.api.client +import kotlinx.serialization.json.Json +import org.slf4j.Logger + interface TelegramBotApiContext { val botApiClient: TelegramBotApiClient + val logger: Logger + val json: Json } + +data class SimpleTelegramBotApiContext( + override val botApiClient: TelegramBotApiClient, + override val logger: Logger, + override val json: Json +) : TelegramBotApiContext diff --git a/src/main/kotlin/me/alllex/tbot/api/client/TelegramBotApiPoller.kt b/src/main/kotlin/me/alllex/tbot/api/client/TelegramBotApiPoller.kt index ed7d54b..7138948 100644 --- a/src/main/kotlin/me/alllex/tbot/api/client/TelegramBotApiPoller.kt +++ b/src/main/kotlin/me/alllex/tbot/api/client/TelegramBotApiPoller.kt @@ -1,205 +1,62 @@ package me.alllex.tbot.api.client -import kotlinx.coroutines.* -import kotlinx.coroutines.channels.BufferOverflow -import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.collect -import kotlinx.coroutines.flow.takeWhile -import me.alllex.tbot.api.model.Update +import kotlinx.coroutines.flow.flatMapMerge +import kotlinx.coroutines.flow.mapNotNull +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.flow.retryWhen +import kotlinx.coroutines.launch +import kotlinx.serialization.json.Json import me.alllex.tbot.api.model.asSeconds import me.alllex.tbot.api.model.tryGetUpdates import org.slf4j.Logger import org.slf4j.LoggerFactory -import java.util.concurrent.atomic.AtomicBoolean -import java.util.concurrent.atomic.AtomicLong -import kotlin.coroutines.CoroutineContext -import kotlin.coroutines.coroutineContext import kotlin.time.Duration -import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds -@OptIn(ExperimentalCoroutinesApi::class) -class TelegramBotApiPoller( - private val client: TelegramBotApiClient, - private val pollingTimeout: Duration = 10.seconds -) { - - private val started = AtomicBoolean(false) - private val updateOffset = AtomicLong(0) - - private val dispatcher = Dispatchers.IO.limitedParallelism(1) - // should not need sync as long as start/stop are ordered by happens-before - private var pollerCoroutineScope: CoroutineScope? = null - - /** - * When a batch of updates is emitted into this flow, - * the flow suspends emission of a next value until the previous on has been consumed (zero-buffer + suspend on overflow). - * This leads to a behavior that the next batch of updates is not requested from the Bot API until - * the last update from the previous batch is emitted. - * It means that as soon as the last update from a batch is emitted, the poller does not wait for the listeners to - * process it and starts fetching the next batch immediately (in doing so, it confirms that the previous batch can be dropped on the Bot API side). - */ - private val _updates: MutableSharedFlow = MutableSharedFlow(extraBufferCapacity = 0, onBufferOverflow = BufferOverflow.SUSPEND) - - private val botApiContext = object : TelegramBotApiContext { - override val botApiClient: TelegramBotApiClient get() = client - } - - /** - * Starts polling with the given listener. - * - * Cannot be restarted again. - */ - fun start(listener: TelegramBotUpdateListener) { - check(started.compareAndSet(false, true)) { "Already started" } - - val coroutineScope = CoroutineScope(SupervisorJob() + dispatcher + CoroutineExceptionHandler(::onUnhandledCoroutineException)) - this.pollerCoroutineScope = coroutineScope - - coroutineScope.launch { - _updates.collect { update -> - listener.onUpdateSafely(update) +suspend fun TelegramBotApiClient.startPolling( + listener: TelegramBotUpdateListener, + onUpdateOffset: suspend (Long) -> Unit = {}, + pollingTimeout: Duration = 10.seconds, + startingUpdateOffset: Long = 0L, + logger: Logger = LoggerFactory.getLogger("TelegramBotApiPoller") +) = coroutineScope { + + var currentUpdateOffset = startingUpdateOffset + val botApiContext = SimpleTelegramBotApiContext( + botApiClient = this@startPolling, + logger = logger, + json = Json(TelegramBotApiClient.JSON) { + prettyPrint = true + } + ) + + timerFlow(1.seconds) { tryGetUpdates(offset = currentUpdateOffset, timeout = pollingTimeout.asSeconds) } + .mapNotNull { it.result } + .onEach { + val highestUpdateId = it.maxOfOrNull { it.updateId } + if (highestUpdateId != null) { + val newUpdateId = highestUpdateId + 1 + onUpdateOffset(newUpdateId) + currentUpdateOffset = newUpdateId } } - - coroutineScope.launch { - // have to await, because the collector registration happens concurrently - // and as soon as there is at least one collector the polling will start immediately - // which could lead to the remaining collectors to skip updates if they start collecting later - _updates.awaitCollectors(n = 1) - - runPollingForever() - } - - log.info("Started") - } - - fun runForever(listener: TelegramBotUpdateListener) { - start(listener) - - runBlocking { - pollerCoroutineScope!!.coroutineContext.job.join() - } - } - - suspend fun stop() { - val pollerJob = pollerCoroutineScope!!.coroutineContext.job - try { - pollerJob.cancelAndJoin() - log.info("Polling job stopped successfully") - } catch (e: CancellationException) { - throw e - } catch (e: Throwable) { - log.error("Failed to gracefully stop polling job", e) - } finally { - pollerCoroutineScope = null - started.set(false) - log.info("Stopped") - } - } - - fun stopBlocking(gracefulAwait: Duration = 500.milliseconds) { - runBlocking { - withTimeout(gracefulAwait) { - stop() + .flatMapMerge { it.asFlow() } + .onEach { + launch { + with(botApiContext) { + listener.onUpdate(it) + } } } - } - - private suspend fun TelegramBotUpdateListener.onUpdateSafely(update: Update) { - try { - with(botApiContext) { - onUpdate(update) - } - } catch (e: CancellationException) { - throw e - } catch (e: Throwable) { - log.error("Failed to process update $update", e) - } - } - - private suspend fun runPollingForever() { - while (coroutineContext.isActive) { - runPollingIteration() + .retryWhen { cause, attempt -> + logger.error("Failed to process update", cause) + attempt < 10 } - } + .collect() - private suspend fun runPollingIteration() { - val updates = fetchUpdatesSafelyRetryingForever() ?: return - log.debug("Received ${updates.size} updates") - - for (update in updates) { - _updates.emit(update) // cancellable - val updateId = update.updateId - updateOffset.updateAndGet { maxOf(it, updateId + 1) } - } - } - - private suspend fun fetchUpdatesSafelyRetryingForever(): List? { - // happy path - fetchUpdatesSafely()?.let { return it } - - // 1, 2, 4, 8, 10, 10, ... - val retryDelaySeconds = generateSequence(1) { it * 2 }.map { it.coerceAtMost(10) } - - for (delaySeconds in retryDelaySeconds) { - if (!coroutineContext.isActive) break - - fetchUpdatesSafely()?.let { return it } - - log.warn("Retrying update fetching in $delaySeconds seconds...") - delay(delaySeconds * 1000L) - } - - // Should not get here - return null - } - - /** - * Returns fetched updates or null if an error occurred. - */ - private suspend fun fetchUpdatesSafely(): List? { - return try { - fetchUpdates() - } catch (e: CancellationException) { - throw e - } catch (e: Throwable) { - log.error("Failed to get updates due to unexpected error:", e) - null - } - } - - private suspend fun fetchUpdates(): List? { - val updateOffsetValue = updateOffset.get() - log.debug("Fetching updates with offset $updateOffsetValue") - val response = client.tryGetUpdates(updateOffsetValue, timeout = pollingTimeout.asSeconds) - if (response.ok) { - return response.result - } - - log.error("Failed to get updates: $response") - - val retryAfter = response.parameters?.retryAfter - if (retryAfter != null) { - log.warn("Too many requests, Bot API asks to retry after $retryAfter seconds. Suspending requests for this time...") - delay(retryAfter.value * 1000L) - return null - } - - return null - } - - companion object { - - private val log: Logger = LoggerFactory.getLogger(TelegramBotApiPoller::class.java) - - private fun onUnhandledCoroutineException(context: CoroutineContext, throwable: Throwable) { - log.error("Unhandled coroutine exception in $context", throwable) - } - - private suspend fun MutableSharedFlow.awaitCollectors(n: Int = 1) { - subscriptionCount.takeWhile { it < n }.collect() - } - } } + diff --git a/src/main/kotlin/me/alllex/tbot/api/client/TelegramBotUpdateListener.kt b/src/main/kotlin/me/alllex/tbot/api/client/TelegramBotUpdateListener.kt index befe095..99ff371 100644 --- a/src/main/kotlin/me/alllex/tbot/api/client/TelegramBotUpdateListener.kt +++ b/src/main/kotlin/me/alllex/tbot/api/client/TelegramBotUpdateListener.kt @@ -1,6 +1,30 @@ package me.alllex.tbot.api.client -import me.alllex.tbot.api.model.* +import me.alllex.tbot.api.model.CallbackQuery +import me.alllex.tbot.api.model.CallbackQueryUpdate +import me.alllex.tbot.api.model.ChannelPostUpdate +import me.alllex.tbot.api.model.ChatJoinRequest +import me.alllex.tbot.api.model.ChatJoinRequestUpdate +import me.alllex.tbot.api.model.ChatMemberUpdate +import me.alllex.tbot.api.model.ChatMemberUpdated +import me.alllex.tbot.api.model.ChosenInlineResult +import me.alllex.tbot.api.model.ChosenInlineResultUpdate +import me.alllex.tbot.api.model.EditedChannelPostUpdate +import me.alllex.tbot.api.model.EditedMessageUpdate +import me.alllex.tbot.api.model.InlineQuery +import me.alllex.tbot.api.model.InlineQueryUpdate +import me.alllex.tbot.api.model.Message +import me.alllex.tbot.api.model.MessageUpdate +import me.alllex.tbot.api.model.MyChatMemberUpdate +import me.alllex.tbot.api.model.Poll +import me.alllex.tbot.api.model.PollAnswer +import me.alllex.tbot.api.model.PollAnswerUpdate +import me.alllex.tbot.api.model.PollUpdate +import me.alllex.tbot.api.model.PreCheckoutQuery +import me.alllex.tbot.api.model.PreCheckoutQueryUpdate +import me.alllex.tbot.api.model.ShippingQuery +import me.alllex.tbot.api.model.ShippingQueryUpdate +import me.alllex.tbot.api.model.Update interface TelegramBotUpdateListener { diff --git a/src/main/kotlin/me/alllex/tbot/api/client/TelegramResponse.kt b/src/main/kotlin/me/alllex/tbot/api/client/TelegramResponse.kt index af08bd8..e34502f 100644 --- a/src/main/kotlin/me/alllex/tbot/api/client/TelegramResponse.kt +++ b/src/main/kotlin/me/alllex/tbot/api/client/TelegramResponse.kt @@ -2,10 +2,9 @@ package me.alllex.tbot.api.client import kotlinx.serialization.Serializable import me.alllex.tbot.api.model.ResponseParameters -import kotlin.jvm.Throws @Serializable -data class TelegramResponse( +data class TelegramResponse( val result: T? = null, val ok: Boolean, val description: String? = null, diff --git a/src/main/kotlin/me/alllex/tbot/api/client/Utils.kt b/src/main/kotlin/me/alllex/tbot/api/client/Utils.kt new file mode 100644 index 0000000..4c92509 --- /dev/null +++ b/src/main/kotlin/me/alllex/tbot/api/client/Utils.kt @@ -0,0 +1,20 @@ +package me.alllex.tbot.api.client + +import io.ktor.client.plugins.HttpTimeout +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.flow +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds + +internal var HttpTimeout.HttpTimeoutCapabilityConfiguration.requestTimeout: Duration? + get() = requestTimeoutMillis?.milliseconds + set(value) { + requestTimeoutMillis = value?.inWholeMilliseconds + } + +internal fun timerFlow(interval: Duration, function: suspend () -> T) = flow { + while (true) { + delay(interval) + emit(function()) + } +} diff --git a/src/main/kotlin/me/alllex/tbot/api/dsl/TelegramBotUpdateBuilder.kt b/src/main/kotlin/me/alllex/tbot/api/dsl/TelegramBotUpdateBuilder.kt new file mode 100644 index 0000000..165e277 --- /dev/null +++ b/src/main/kotlin/me/alllex/tbot/api/dsl/TelegramBotUpdateBuilder.kt @@ -0,0 +1,125 @@ +package me.alllex.tbot.api.dsl + +import me.alllex.tbot.api.client.TelegramBotApiClient +import me.alllex.tbot.api.client.TelegramBotApiContext +import me.alllex.tbot.api.client.TelegramBotUpdateListener +import me.alllex.tbot.api.client.startPolling +import me.alllex.tbot.api.model.CallbackQuery +import me.alllex.tbot.api.model.ChatJoinRequest +import me.alllex.tbot.api.model.ChatMemberUpdated +import me.alllex.tbot.api.model.ChosenInlineResult +import me.alllex.tbot.api.model.InlineQuery +import me.alllex.tbot.api.model.Message +import me.alllex.tbot.api.model.Poll +import me.alllex.tbot.api.model.PollAnswer +import me.alllex.tbot.api.model.PreCheckoutQuery +import me.alllex.tbot.api.model.ShippingQuery +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds + +class TelegramBotUpdateBuilder { + + private var onMessage: (suspend context(TelegramBotApiContext) (Message) -> Unit)? = null + private var onEditedMessage: (suspend context(TelegramBotApiContext) (Message) -> Unit)? = null + private var onChannelPost: (suspend context(TelegramBotApiContext) (Message) -> Unit)? = null + private var onEditedChannelPost: (suspend context(TelegramBotApiContext) (Message) -> Unit)? = null + private var onInlineQuery: (suspend context(TelegramBotApiContext) (InlineQuery) -> Unit)? = null + private var onChosenInlineResult: (suspend context(TelegramBotApiContext) (ChosenInlineResult) -> Unit)? = null + private var onCallbackQuery: (suspend context(TelegramBotApiContext) (CallbackQuery) -> Unit)? = null + private var onShippingQuery: (suspend context(TelegramBotApiContext) (ShippingQuery) -> Unit)? = null + private var onPreCheckoutQuery: (suspend context(TelegramBotApiContext) (PreCheckoutQuery) -> Unit)? = null + private var onPoll: (suspend context(TelegramBotApiContext) (Poll) -> Unit)? = null + private var onPollAnswer: (suspend context(TelegramBotApiContext) (PollAnswer) -> Unit)? = null + private var onMyChatMember: (suspend context(TelegramBotApiContext) (ChatMemberUpdated) -> Unit)? = null + private var onChatMember: (suspend context(TelegramBotApiContext) (ChatMemberUpdated) -> Unit)? = null + private var onChatJoinRequest: (suspend context(TelegramBotApiContext) (ChatJoinRequest) -> Unit)? = null + + fun onMessage(action: suspend context(TelegramBotApiContext) (Message) -> Unit) { + onMessage = action + } + + fun onEditedMessage(action: suspend context(TelegramBotApiContext) (Message) -> Unit) { + onEditedMessage = action + } + + fun onChannelPost(action: suspend context(TelegramBotApiContext) (Message) -> Unit) { + onChannelPost = action + } + + fun onEditedChannelPost(action: suspend context(TelegramBotApiContext) (Message) -> Unit) { + onEditedMessage = action + } + + fun onInlineQuery(action: suspend context(TelegramBotApiContext) (InlineQuery) -> Unit) { + onInlineQuery = action + } + + fun onChosenInlineResult(action: suspend context(TelegramBotApiContext) (ChosenInlineResult) -> Unit) { + onChosenInlineResult = action + } + + fun onCallbackQuery(action: suspend context(TelegramBotApiContext) (CallbackQuery) -> Unit) { + onCallbackQuery = action + } + + fun onShippingQuery(action: suspend context(TelegramBotApiContext) (ShippingQuery) -> Unit) { + onShippingQuery = action + } + + fun onPreCheckoutQuery(action: suspend context(TelegramBotApiContext) (PreCheckoutQuery) -> Unit) { + onPreCheckoutQuery = action + } + + fun onPoll(action: suspend context(TelegramBotApiContext) (Poll) -> Unit) { + onPoll = action + } + + fun onPollAnswer(action: suspend context(TelegramBotApiContext) (PollAnswer) -> Unit) { + onPollAnswer = action + } + + fun onMyChatMember(action: suspend context(TelegramBotApiContext) (ChatMemberUpdated) -> Unit) { + onMyChatMember = action + } + + fun onChatMember(action: suspend context(TelegramBotApiContext) (ChatMemberUpdated) -> Unit) { + onChatMember = action + } + + fun onChatJoinRequest(action: suspend context(TelegramBotApiContext) (ChatJoinRequest) -> Unit) { + onChatJoinRequest = action + } + + fun build() = TelegramBotUpdateListener( + onMessage = onMessage, + onEditedMessage = onEditedMessage, + onChannelPost = onChannelPost, + onEditedChannelPost = onEditedChannelPost, + onInlineQuery = onInlineQuery, + onChosenInlineResult = onChosenInlineResult, + onCallbackQuery = onCallbackQuery, + onShippingQuery = onShippingQuery, + onPreCheckoutQuery = onPreCheckoutQuery, + onPoll = onPoll, + onPollAnswer = onPollAnswer, + onMyChatMember = onMyChatMember, + onChatMember = onChatMember, + onChatJoinRequest = onChatJoinRequest + ) +} + +suspend fun TelegramBotApiClient.startPolling( + pollingTimeout: Duration = 0.seconds, + startingUpdateOffset: Long = 0L, + logger: Logger = LoggerFactory.getLogger("TelegramBotApiPoller"), + onUpdateOffset: suspend (Long) -> Unit = {}, + listener: TelegramBotUpdateBuilder.() -> Unit +) = startPolling( + listener = TelegramBotUpdateBuilder().apply(listener).build(), + onUpdateOffset = onUpdateOffset, + pollingTimeout = pollingTimeout, + startingUpdateOffset = startingUpdateOffset, + logger = logger +) diff --git a/src/test/kotlin/me/alllex/tbot/api/client/TelegramBotApiClientTest.kt b/src/test/kotlin/me/alllex/tbot/api/client/TelegramBotApiClientTest.kt index 7a7ea7a..fa83ed5 100644 --- a/src/test/kotlin/me/alllex/tbot/api/client/TelegramBotApiClientTest.kt +++ b/src/test/kotlin/me/alllex/tbot/api/client/TelegramBotApiClientTest.kt @@ -4,15 +4,34 @@ import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.isInstanceOf import assertk.assertions.prop -import io.ktor.client.engine.mock.* -import io.ktor.client.utils.* -import io.ktor.content.* -import io.ktor.http.* -import org.junit.jupiter.api.Test - +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.respond +import io.ktor.client.utils.EmptyContent +import io.ktor.content.TextContent +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpMethod +import io.ktor.http.HttpStatusCode +import io.ktor.http.headersOf import io.ktor.utils.io.ByteReadChannel import kotlinx.coroutines.test.runTest -import me.alllex.tbot.api.model.* +import me.alllex.tbot.api.model.Chat +import me.alllex.tbot.api.model.ChatId +import me.alllex.tbot.api.model.InlineKeyboardButton +import me.alllex.tbot.api.model.InlineKeyboardMarkup +import me.alllex.tbot.api.model.InlineQuery +import me.alllex.tbot.api.model.InlineQueryId +import me.alllex.tbot.api.model.InlineQueryUpdate +import me.alllex.tbot.api.model.Message +import me.alllex.tbot.api.model.MessageId +import me.alllex.tbot.api.model.MessageUpdate +import me.alllex.tbot.api.model.UnixTimestamp +import me.alllex.tbot.api.model.UpdateType +import me.alllex.tbot.api.model.User +import me.alllex.tbot.api.model.UserId +import me.alllex.tbot.api.model.tryGetMe +import me.alllex.tbot.api.model.tryGetUpdates +import me.alllex.tbot.api.model.trySendMessage +import org.junit.jupiter.api.Test import kotlin.test.assertEquals @@ -32,7 +51,11 @@ class TelegramBotApiClientTest { ) } - val client = TelegramBotApiClient("Token", host = "bot.test", engine = engine) + val client = TelegramBotApiClient( + apiToken = "Token", + apiHost = "bot.test", + httpClient = TelegramBotApiClient.httpClient(engine) + ) val actualResponse = client.tryGetMe() @@ -64,7 +87,11 @@ class TelegramBotApiClientTest { ) } - val client = TelegramBotApiClient("Token", host = "bot.test", engine = engine) + val client = TelegramBotApiClient( + apiToken = "Token", + apiHost = "bot.test", + httpClient = TelegramBotApiClient.httpClient(engine) + ) val actualResponse = client.tryGetMe() @@ -100,7 +127,11 @@ class TelegramBotApiClientTest { ) } - val client = TelegramBotApiClient("Token", host = "bot.test", engine = engine) + val client = TelegramBotApiClient( + apiToken = "Token", + apiHost = "bot.test", + httpClient = TelegramBotApiClient.httpClient(engine) + ) val actualResponse = client.tryGetUpdates( allowedUpdates = listOf(UpdateType.MESSAGE, UpdateType.INLINE_QUERY) @@ -147,7 +178,8 @@ class TelegramBotApiClientTest { assertThat(request.url.toString()).isEqualTo("https://bot.test/botToken/sendMessage") assertThat(request.method).isEqualTo(HttpMethod.Post) assertThat(request.body).isInstanceOf() - .prop(TextContent::text).isEqualTo("""{"chat_id":1,"text":"Hello","reply_markup":{"inline_keyboard":[[{"text":"Button"}]]}}""") + .prop(TextContent::text) + .isEqualTo("""{"chat_id":1,"text":"Hello","reply_markup":{"inline_keyboard":[[{"text":"Button"}]]}}""") respond( content = ByteReadChannel( @@ -166,7 +198,11 @@ class TelegramBotApiClientTest { ) } - val client = TelegramBotApiClient("Token", host = "bot.test", engine = engine) + val client = TelegramBotApiClient( + apiToken = "Token", + apiHost = "bot.test", + httpClient = TelegramBotApiClient.httpClient(engine) + ) val actualResponse = client.trySendMessage( chatId = ChatId(1), diff --git a/src/test/kotlin/me/alllex/tbot/api/client/TelegramBotApiPollerTest.kt b/src/test/kotlin/me/alllex/tbot/api/client/TelegramBotApiPollerTest.kt index 7e3769a..f28bc28 100644 --- a/src/test/kotlin/me/alllex/tbot/api/client/TelegramBotApiPollerTest.kt +++ b/src/test/kotlin/me/alllex/tbot/api/client/TelegramBotApiPollerTest.kt @@ -4,31 +4,34 @@ import assertk.all import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.prop -import io.ktor.client.engine.mock.* -import io.ktor.client.request.* -import io.ktor.content.* -import io.ktor.http.* +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.MockRequestHandleScope +import io.ktor.client.engine.mock.respond +import io.ktor.client.request.HttpResponseData +import io.ktor.content.TextContent +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.http.headersOf import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.launch import kotlinx.coroutines.test.runTest -import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonNamingStrategy -import me.alllex.tbot.api.model.* +import me.alllex.tbot.api.dsl.startPolling +import me.alllex.tbot.api.model.Chat +import me.alllex.tbot.api.model.ChatId +import me.alllex.tbot.api.model.GetUpdatesRequest +import me.alllex.tbot.api.model.Message +import me.alllex.tbot.api.model.MessageId +import me.alllex.tbot.api.model.MessageUpdate +import me.alllex.tbot.api.model.UnixTimestamp import org.junit.jupiter.api.Test import org.slf4j.LoggerFactory import kotlin.test.fail -@OptIn(ExperimentalSerializationApi::class) class TelegramBotApiPollerTest { - private val json = Json { - namingStrategy = JsonNamingStrategy.SnakeCase - explicitNulls = false - } - private inline fun MockRequestHandleScope.respondOk(body: T): HttpResponseData = respond( - content = json.encodeToString(TelegramResponse(ok = true, result = body)), + content = TelegramBotApiClient.JSON.encodeToString(TelegramResponse(ok = true, result = body)), status = HttpStatusCode.OK, headers = headersOf(HttpHeaders.ContentType, "application/json") ) @@ -44,7 +47,7 @@ class TelegramBotApiPollerTest { val requestBodyText = (request.body as TextContent).text when { url.endsWith("/getUpdates") -> { - val body = json.decodeFromString(requestBodyText) + val body = TelegramBotApiClient.JSON.decodeFromString(requestBodyText) when (body.offset?.toInt()) { 0 -> { log.info("[TEST] API: Responding with 1 message") @@ -81,23 +84,28 @@ class TelegramBotApiPollerTest { } - val client = TelegramBotApiClient(":testToken", host = "bot.test", engine = engine) - val poller = TelegramBotApiPoller(client) - - poller.start(TelegramBotUpdateListener( - onMessage = { message -> - log.info("[TEST] Received message: $message") - assertThat(message).all { - prop(Message::text).isEqualTo("Message 1") + val client = TelegramBotApiClient( + apiToken = ":testToken", + apiHost = "bot.test", + httpClient = TelegramBotApiClient.httpClient(engine) + ) + + val poller = launch { + client.startPolling { + onMessage { message -> + log.info("[TEST] Received message: $message") + assertThat(message).all { + prop(Message::text).isEqualTo("Message 1") + } } } - )) + } log.info("[TEST] Waiting for deferred for stop") deferredStop.await() log.info("[TEST] Stopping poller") - poller.stop() + poller.cancel() log.info("[TEST] Completing deferred for end") deferredEnd.complete(true) diff --git a/src/test/kotlin/me/alllex/tbot/demo/EchoBot.kt b/src/test/kotlin/me/alllex/tbot/demo/EchoBot.kt index 2d4169a..635526b 100644 --- a/src/test/kotlin/me/alllex/tbot/demo/EchoBot.kt +++ b/src/test/kotlin/me/alllex/tbot/demo/EchoBot.kt @@ -1,14 +1,19 @@ package me.alllex.tbot.demo +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.sync.Mutex import me.alllex.tbot.api.client.TelegramBotApiClient -import me.alllex.tbot.api.client.TelegramBotApiPoller -import me.alllex.tbot.api.client.TelegramBotUpdateListener -import me.alllex.tbot.api.model.* -import java.util.concurrent.CountDownLatch +import me.alllex.tbot.api.dsl.startPolling +import me.alllex.tbot.api.model.answer +import me.alllex.tbot.api.model.button +import me.alllex.tbot.api.model.copyMessage +import me.alllex.tbot.api.model.inlineKeyboard +import me.alllex.tbot.api.model.selfCheck -fun main(args: Array) { +suspend fun main(args: Array) = coroutineScope { check(args.size >= 2) { "Expected 2 arguments" } val (botApiToken, botUsername) = args @@ -17,36 +22,36 @@ fun main(args: Array) { println("Checking bot info...") runBlocking { client.selfCheck(botUsername) } println("Bot info is OK") + val mutex = Mutex(true) - val poller = TelegramBotApiPoller(client) - val countDownLatch = CountDownLatch(1) - - val listener = TelegramBotUpdateListener( - onMessage = { message -> - println("Received message: $message") - val text = message.text - if (text.equals("stop", ignoreCase = true)) { - println("Received stop command, stopping...") - countDownLatch.countDown() - } else { - println("Echoing the message back to the chat...") - message.copyMessage(message.chat.id, replyToMessageId = message.messageId, replyMarkup = inlineKeyboard { - button("Button", "wow") - }) + println("Starting bot...") + val poller = launch { + client.startPolling { + onMessage { message -> + println("Received message: $message") + val text = message.text + if (text.equals("stop", ignoreCase = true)) { + println("Received stop command, stopping...") + mutex.unlock() + } else { + println("Echoing the message back to the chat...") + message.copyMessage( + message.chat.id, + replyToMessageId = message.messageId, + replyMarkup = inlineKeyboard { + button("Button", "wow") + }) + } + } + onCallbackQuery { callbackQuery -> + println("Received callback query: $callbackQuery") + callbackQuery.answer("Wow!") } - }, - onCallbackQuery = { callbackQuery -> - println("Received callback query: $callbackQuery") - callbackQuery.answer("Wow!") } - ) - - println("Starting bot...") - poller.start(listener) - println("Bot started") + } - countDownLatch.await() - poller.stopBlocking() + mutex.lock() + poller.cancel() println("Done") }