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

46 lines
2.3 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.send.sendTextMessage
import dev.inmo.tgbotapi.extensions.api.telegramBot
import dev.inmo.tgbotapi.extensions.utils.*
2020-10-04 11:32:50 +00:00
import dev.inmo.tgbotapi.extensions.utils.formatting.codeMarkdownV2
import dev.inmo.tgbotapi.extensions.utils.formatting.regularMarkdownV2
2020-11-02 08:39:36 +00:00
import dev.inmo.tgbotapi.extensions.utils.shortcuts.mediaGroupMessages
2020-10-04 11:32:50 +00:00
import dev.inmo.tgbotapi.extensions.utils.updates.asContentMessagesFlow
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.ParseMode.MarkdownV2
import dev.inmo.tgbotapi.types.message.*
2020-06-02 14:24:41 +00:00
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
/**
* This bot will always return message about forwarder. In cases when sent message was not a forward message it will
* send suitable message
*/
suspend fun main(vararg args: String) {
val botToken = args.first()
val bot = telegramBot(botToken)
val scope = CoroutineScope(Dispatchers.Default)
2021-03-12 09:48:31 +00:00
bot.longPolling(scope = scope) {
(merge(messageFlow.asContentMessagesFlow(), mediaGroupMessages(scope).flatMap())).mapNotNull { it.asPossiblyForwardedMessage() }.onEach { message ->
2020-09-12 11:04:59 +00:00
safely({ it.printStackTrace() }) {
2020-06-02 14:24:41 +00:00
val toAnswer = when (val forwardInfo = message.forwardInfo) {
null -> "There is no forward info"
is AnonymousForwardInfo -> "Anonymous user which signed as \"${forwardInfo.senderName.codeMarkdownV2()}\""
is UserForwardInfo -> forwardInfo.from.let { user ->
"User ${user.id.chatId.toString().codeMarkdownV2()} " + "(${user.firstName} ${user.lastName}: ${user.username ?.username ?: "Without username"})".regularMarkdownV2()
}
is ForwardFromChannelInfo -> "Channel (".regularMarkdownV2() + (forwardInfo.channelChat).title.codeMarkdownV2() + ")".regularMarkdownV2()
2020-10-02 12:08:14 +00:00
is ForwardFromSupergroupInfo -> "Supergroup (".regularMarkdownV2() + (forwardInfo.group).title.codeMarkdownV2() + ")".regularMarkdownV2()
2020-06-02 14:24:41 +00:00
}
bot.sendTextMessage(message.chat, toAnswer, MarkdownV2)
}
}.launchIn(scope)
}
scope.coroutineContext[Job]!!.join()
}