Martin Gaens
07/11/2022, 12:34 AMprivate val client = HttpClient(CIO) {
install(DefaultRequest)
install(ContentNegotiation) {
json(Config.json)
}
install(HttpTimeout) {
connectTimeoutMillis = 30_000
requestTimeoutMillis = 30_000
}
install(Logging) {
level = LogLevel.ALL
}
defaultRequest {
url("<https://api.telegram.org/bot${bot.token}/>")
}
}
And this is how I handle the updates:
internal val updateFlow: Flow<Update> = flow {
while (true) {
try {
val updates = getUpdates(
offset = currentOffset,
timeout = KramBot.LONG_POLLING_TIMEOUT_SECONDS
)
// Telegram servers return an empty JSON array after the timeout if there are no updates
if (updates.isEmpty()) continue
updates.forEach { emit(it) }
currentOffset = updates.last().updateId + 1
} catch (e: HttpRequestTimeoutException) {
println("Timed out.")
}
}
}
private suspend fun getUpdates(
offset: Int? = null,
limit: Int? = null,
timeout: Int? = null,
allowedUpdates: List<String>? = null
): List<Update> {
val response = <http://client.post|client.post>("getUpdates") {
with(url.parameters) {
offset?.let { append("offset", it.toString()) }
limit?.let { append("limit", it.toString()) }
timeout?.let { append("timeout", it.toString()) }
allowedUpdates?.let { append("allowed_updates", it.toString()) }
}
}
when (val apiResponse = response.body<ApiResponse<List<UpdateDto>>>()) {
is ApiResponse.Ok -> return apiResponse.result.map { it.toEntity() }
is ApiResponse.Error -> error(
"""
Got an error response from the getUpdates method which should be impossible.
Error code: ${apiResponse.errorCode}
Description: ${apiResponse.description}
""".trimIndent()
)
}
}
getUpdates
url in Firefox, it responds immediately to my messages. However, Ktor takes about a second to do so. Why is that?
suspend fun main() {
val offset = "547767852"
val timeout = "30"
val address = "<https://api.telegram.org/bot123456789:qwertyuiopasdfghjklzxcvbnm/getUpdates>"
val client = HttpClient(CIO) {
install(HttpTimeout) {
connectTimeoutMillis = 30_000
requestTimeoutMillis = 30_000
}
}
val response = <http://client.post|client.post>(address) {
with(url.parameters) {
append("offset", offset)
append("timeout", timeout)
}
}
println(response.bodyAsText())
}
Aleksei Tirman [JB]
07/11/2022, 10:25 AMMartin Gaens
07/11/2022, 10:26 AMAleksei Tirman [JB]
07/11/2022, 4:22 PMMartin Gaens
07/11/2022, 6:07 PMAleksei Tirman [JB]
07/12/2022, 11:41 AMIs this issue only present when contacting Telegram servers?To answer this question deeper investigation is required.
Martin Gaens
07/12/2022, 12:06 PM