I am writing a telegram bot api wrapper on kotlin using ktor and came across a problem - I just can't figure out how to upload files to tda.
Tba provides 3 ways to upload files (Excerpt from documentation ):
There are three ways to send files (photos, stickers, audio, media, etc.):
- There is a file_id field, simply a file_id field. There are no limits for files sent this way.
- Provide Telegram with an HTTP URL Telegram will download and send the file. 5 MB max size for photos and 20 MB max for other types of content.
- Post the file using multipart / form-data in the usual way that files are uploaded via the browser. 10 MB max size for photos, 50 MB for other files.
file_id files by URL and file_id is clear and works.
Now I have such a terrible function here, makes a request to tba and parses the answer:
suspend fun <T> makeRequest(token: String, method: TelegramMethod, vararg params: Pair<String, Any?>, files: Map<String, String> = emptyMap()): T { try { val data: List<PartData> = formData { files.forEach { key, fileName -> append(key, Files.newInputStream(Paths.get(fileName)).asInput()) } } val response = client.submitFormWithBinaryData<HttpResponse>(data) { this.method = HttpMethod.Post url { protocol = URLProtocol("https", 42) host = API_HOST encodedPath = API_PATH_PATTERN.format(token, method.methodName) params.forEach { (name, value) -> if (value != null) this.parameters[name] = value as String } } } val result = response.receive<String>() return parseTelegramAnswer<T>(response, result) } catch (e: BadResponseStatusException) { throw checkTelegramError(e) } } It works without files, but not with files. (I probably send the files somehow not at all correctly).
I tested on different files, here is the result:
- sending files weighing from
17,9 KiBand up to56,6 KiBI received aBad Request: wrong URL hosterror from the telegramBad Request: wrong URL host - sending files weighing from
75,6 KiBand up to913,2 KiBI received an error413 Request Entity Too
* I used the sendDocument method and sent photos
How to send files using ktor ?