69 lines
2.6 KiB
Kotlin
69 lines
2.6 KiB
Kotlin
package dev.inmo.postssystem.targets.telegram.publication.server
|
|
|
|
import dev.inmo.micro_utils.mime_types.KnownMimeTypes
|
|
import dev.inmo.postssystem.features.content.common.BinaryContent
|
|
import dev.inmo.postssystem.features.content.text.common.TextContent
|
|
import dev.inmo.postssystem.features.publication.server.PublicationPost
|
|
import dev.inmo.postssystem.features.publication.server.PublicationTarget
|
|
import dev.inmo.tgbotapi.bot.TelegramBot
|
|
import dev.inmo.tgbotapi.extensions.utils.shortcuts.executeUnsafe
|
|
import dev.inmo.tgbotapi.requests.abstracts.MultipartFile
|
|
import dev.inmo.tgbotapi.requests.abstracts.asMultipartFile
|
|
import dev.inmo.tgbotapi.requests.send.SendTextMessage
|
|
import dev.inmo.tgbotapi.requests.send.media.*
|
|
import dev.inmo.tgbotapi.types.ChatId
|
|
import io.ktor.utils.io.ByteReadChannel
|
|
import io.ktor.utils.io.core.readBytes
|
|
import kotlinx.coroutines.delay
|
|
|
|
class PublicationTargetTelegram(
|
|
private val bot: TelegramBot,
|
|
private val targetChatId: ChatId
|
|
) : PublicationTarget {
|
|
override suspend fun publish(post: PublicationPost) {
|
|
post.content.mapNotNull {
|
|
when (val content = it.content) {
|
|
is BinaryContent -> {
|
|
val storageFile by lazy {
|
|
MultipartFile(content.filename.name) {
|
|
content.inputProvider()
|
|
}
|
|
}
|
|
when (content.mimeType) {
|
|
is KnownMimeTypes.Image.Jpeg,
|
|
is KnownMimeTypes.Image.Png -> {
|
|
SendPhoto(targetChatId, storageFile)
|
|
}
|
|
is KnownMimeTypes.Video.Mp4 -> {
|
|
SendVideo(targetChatId, storageFile)
|
|
}
|
|
is KnownMimeTypes.Audio.Mpeg -> {
|
|
SendAudio(targetChatId, storageFile)
|
|
}
|
|
else -> SendDocument(
|
|
targetChatId,
|
|
storageFile
|
|
)
|
|
}
|
|
}
|
|
is TextContent -> {
|
|
SendTextMessage(targetChatId, content.text)
|
|
}
|
|
else -> null
|
|
}
|
|
}.forEach { request ->
|
|
repeat(3) {
|
|
runCatching {
|
|
bot.execute(request)
|
|
}.onFailure {
|
|
it.printStackTrace()
|
|
}.onSuccess {
|
|
return@forEach
|
|
}
|
|
delay(1000L)
|
|
}
|
|
delay(100L)
|
|
}
|
|
}
|
|
}
|