TelegramBotAPI-examples/FilesLoaderBot/src/main/kotlin/FilesLoaderBot.kt

43 lines
1.5 KiB
Kotlin
Raw Normal View History

2021-01-18 17:32:47 +00:00
import dev.inmo.micro_utils.coroutines.safely
import dev.inmo.tgbotapi.bot.Ktor.telegramBot
2020-10-04 11:32:50 +00:00
import dev.inmo.tgbotapi.extensions.api.downloadFile
import dev.inmo.tgbotapi.extensions.api.get.getFileAdditionalInfo
import dev.inmo.tgbotapi.extensions.utils.flatMap
import dev.inmo.tgbotapi.extensions.utils.shortcuts.*
2021-03-12 09:48:31 +00:00
import dev.inmo.tgbotapi.extensions.utils.updates.retrieving.longPolling
2020-10-04 11:32:50 +00:00
import dev.inmo.tgbotapi.types.message.content.abstracts.MediaContent
import dev.inmo.tgbotapi.utils.filenameFromUrl
2020-08-23 15:52:13 +00:00
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import java.io.File
/**
* This bot will download incoming files
*/
suspend fun main(args: Array<String>) {
val botToken = args.first()
val directoryOrFile = args.getOrNull(1) ?.let { File(it) } ?: File("")
directoryOrFile.mkdirs()
val bot = telegramBot(botToken)
val scope = CoroutineScope(Dispatchers.Default)
2021-03-12 09:48:31 +00:00
bot.longPolling(scope = scope) {
2020-08-23 15:52:13 +00:00
val flow = merge (
filterContentMessages<MediaContent>(),
mediaGroupMessages().flatMap()
)
flow.onEach {
safely({ it.printStackTrace() }) {
val pathedFile = bot.getFileAdditionalInfo(it.content.media)
File(directoryOrFile, pathedFile.filePath.filenameFromUrl).apply {
createNewFile()
writeBytes(bot.downloadFile(pathedFile))
}
}
}.launchIn(scope)
}
scope.coroutineContext[Job]!!.join()
}