update examples for ktgbotapi 38.0.0

This commit is contained in:
InsanusMokrassar committed 2026-11-26 12:28:56 +06:00
1 parent d0da6c851b
commit 97b4391495
86 files changed
+888 -370

No files matched your search

+21 -16
View File
@@ -1,31 +1,33 @@
# EphemeralMessagesBot
Demonstrates Telegram Bot API 10.2 and 10.3 ephemeral messages: group messages that Telegram shows only to one receiver.
Demonstrates messages that Telegram shows to a single recipient. A button press supplies the destination for
an ephemeral callback reply. For a direct send in a group, the example supplies both the chat and the receiver.
## Behavior
- `/ephemeral` replies with a **Reveal a secret** inline button. The command is registered with Telegram as
an ephemeral command.
- Pressing the button (`reveal` callback data) uses `EphemeralMessageParameters` to replace the callback-query
message with a personal rich message visible only to the user who pressed it. After three seconds the bot replaces
its text with typed rich blocks, then deletes it three seconds later.
- `/ephemeral_photo` waits for a photo from the same user and chat, sends it back ephemerally by its Telegram file ID,
downloads it, and edits the ephemeral media using a new multipart upload. A second edit sets
- Pressing **Reveal a secret** sends a separate personal rich message with `sendRichMessage(callbackQueryId = …)`.
The bot acknowledges the press with `answer(query)`. Its handler accepts callbacks with either a message or an
inline message ID. It uses the chat returned by the send to edit the secret after three seconds and delete it
three seconds later.
- `/ephemeral_photo` waits for a photo from the same user and chat, then sends it back by its Telegram file ID
with `receiverUserId` set to the user's ID. The bot downloads the photo and edits the ephemeral media using a
new multipart upload. A second edit sets
`showCaptionAboveMedia = true`.
- `/ephemeral_live_photo` waits for a Live Photo, sends it ephemerally by existing file IDs, then downloads and
re-uploads both its main file and secondary `photo` file in one `editEphemeralMessageMedia` request. This exercises
ktgbotapi 37.0.0's secondary multipart attachment collection.
- When the bot receives an ephemeral content message, it sends two ephemeral replies: one through the
general `reply` API and one through the explicit `replyToEphemeral` API. The explicit form also uses
`EphemeralMessageParameters`.
- `/ephemeral_live_photo` waits for a Live Photo from the same user and chat and sends it ephemerally using existing
file IDs. When a cover photo is available, it uploads both the main file and the cover in one
`editEphemeralMessageMedia` request.
- When the bot receives an ephemeral message with an identifiable recipient, it replies twice. The general `reply`
derives the recipient and ephemeral message ID. The explicit `replyToEphemeral` takes the chat ID, recipient ID,
and ephemeral message ID.
- Updates and basic bot information are printed to standard output.
## Setup
Create a bot token, keep it secret, and add the bot to a group. The bot must be allowed to send messages
there; this example does not request or validate group permissions itself. Use a Telegram environment that
supports ephemeral messages. The photo demonstrations download all selected media into memory before uploading it
again.
Add the bot to a group where it can send messages and media. To try either photo command with group privacy mode
enabled, send the photo as a reply to the bot's prompt. The photo demonstrations download the selected media into
memory before uploading it again.
## Run
@@ -39,6 +41,9 @@ Optional, case-sensitive arguments may follow the token:
- `debug` enables formatted library logging on standard output.
- `testServer` connects the bot to Telegram's test server.
- `inlineCallbacks` calls `setMySettings` so that buttons in bot-sent messages produce callbacks with
an inline message ID. Run `/ephemeral` and press its button to try this delivery mode. The setting
persists until you change it. Use `defaultCallbacks` on a later launch to restore Telegram's default.
For example:
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
mainClassName="EphemeralMessagesBotKt"
application.mainClass = "EphemeralMessagesBotKt"
dependencies {
@@ -3,8 +3,10 @@ import dev.inmo.kslog.common.LogLevel
import dev.inmo.kslog.common.defaultMessageFormatter
import dev.inmo.kslog.common.setDefaultKSLog
import dev.inmo.micro_utils.coroutines.subscribeSafelyWithoutExceptions
import dev.inmo.tgbotapi.extensions.api.answers.answer
import dev.inmo.tgbotapi.extensions.api.bot.getMe
import dev.inmo.tgbotapi.extensions.api.bot.setMyCommands
import dev.inmo.tgbotapi.extensions.api.bot.setMySettings
import dev.inmo.tgbotapi.extensions.api.deleteEphemeralMessage
import dev.inmo.tgbotapi.extensions.api.edit.caption.editEphemeralMessageCaption
import dev.inmo.tgbotapi.extensions.api.edit.media.editEphemeralMessageMedia
@@ -20,23 +22,20 @@ import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitPhotoMess
import dev.inmo.tgbotapi.extensions.behaviour_builder.telegramBotWithBehaviourAndLongPolling
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommand
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onContentMessage
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onMessageDataCallbackQuery
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onDataCallbackQuery
import dev.inmo.tgbotapi.extensions.utils.fromUserMessageOrNull
import dev.inmo.tgbotapi.extensions.utils.extensions.sameChat
import dev.inmo.tgbotapi.extensions.utils.types.buttons.dataButton
import dev.inmo.tgbotapi.extensions.utils.types.buttons.flatInlineKeyboard
import dev.inmo.tgbotapi.requests.abstracts.asMultipartFile
import dev.inmo.tgbotapi.types.BotCommand
import dev.inmo.tgbotapi.types.EphemeralMessageParameters
import dev.inmo.tgbotapi.types.directMessageThreadIdOrMessageThreadIdAsDirectMessageThreadId
import dev.inmo.tgbotapi.types.CallbackQueryMode
import dev.inmo.tgbotapi.types.ephemeralReplyReceiverUserIdOrNull
import dev.inmo.tgbotapi.types.media.TelegramMediaLivePhoto
import dev.inmo.tgbotapi.types.media.TelegramMediaPhoto
import dev.inmo.tgbotapi.types.message.abstracts.PossiblyEphemeralMessage
import dev.inmo.tgbotapi.types.rich.InputRichMessageBlocks
import korlibs.time.seconds
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
@@ -44,7 +43,7 @@ import kotlinx.coroutines.flow.first
/**
* Runs the ephemeral-messages example bot using long polling.
*
* `/ephemeral` posts an inline button whose callback replaces it with a rich message visible only to
* `/ephemeral` posts an inline button whose callback sends a separate rich message visible only to
* the user who pressed it, edits that message, and deletes it. `/ephemeral_photo` demonstrates uploading new media
* to an ephemeral edit and moving its caption above the media. `/ephemeral_live_photo` demonstrates collecting both
* multipart files of a Live Photo edit. Incoming [PossiblyEphemeralMessage] instances receive both an automatic
@@ -72,6 +71,10 @@ suspend fun main(vararg args: String) {
botToken,
testServer = isTestServer,
) {
when {
"inlineCallbacks" in args -> setMySettings(callbackQueryMode = CallbackQueryMode.Inline)
"defaultCallbacks" in args -> setMySettings(callbackQueryMode = CallbackQueryMode.Default)
}
val me = getMe()
println("Bot info: $me")
@@ -87,47 +90,37 @@ suspend fun main(vararg args: String) {
)
}
// Bot API 10.3 groups the recipient/callback fields in EphemeralMessageParameters. Setting
// replaceCallbackQueryMessage replaces the button message only for the user who pressed it.
onMessageDataCallbackQuery(Regex("reveal")) { query ->
val chatId = query.message.chat.id
val receiverUserId = query.from.id
// Telegram resolves the destination from the callback, including callbacks carrying an inline message ID.
onDataCallbackQuery("reveal") { query ->
val sent = sendRichMessage(
chatId,
InputRichMessageBlocks {
callbackQueryId = query.id,
richMessage = InputRichMessageBlocks {
paragraph {
plain("🔒 ${query.from.firstName}, here is your personal secret: ")
code("42")
}
},
ephemeralMessageParameters = EphemeralMessageParameters(
receiverUserId = receiverUserId,
callbackQueryId = query.id,
replaceCallbackQueryMessage = false,
),
replaceCallbackQueryMessage = false,
)
answer(query)
// Only the group-family Common*ContentMessage types implement PossiblyEphemeralMessage, so the
// sent ephemeral message exposes its ephemeralMessageId through that interface.
val ephemeralMessageId = (sent as? PossiblyEphemeralMessage)?.ephemeralMessageId
if (ephemeralMessageId != null) {
delay(3.seconds)
// editEphemeralMessageText now accepts rich_message; the typed extension exposes that as
// editEphemeralMessageRichText.
editEphemeralMessageRichText(
chatId,
receiverUserId,
ephemeralMessageId,
InputRichMessageBlocks {
h2("Secret revealed")
paragraph { plain("The answer is "); code("42") }
},
)
delay(3.seconds)
// deleteEphemeralMessage: same addressing (there is also a PossiblyEphemeralMessage overload)
deleteEphemeralMessage(chatId, receiverUserId, ephemeralMessageId)
}
?: return@onDataCallbackQuery
delay(3.seconds)
editEphemeralMessageRichText(
sent.chat.id,
query.from.id,
ephemeralMessageId,
InputRichMessageBlocks {
h2("Secret revealed")
paragraph {
plain("The answer is ")
code("42")
}
},
)
delay(3.seconds)
deleteEphemeralMessage(sent.chat.id, query.from.id, ephemeralMessageId)
}
// Upload a received photo again as a brand-new multipart file while editing an ephemeral media message.
@@ -142,7 +135,7 @@ suspend fun main(vararg args: String) {
photoMessage.chat.id,
photoMessage.content.media.fileId,
text = "Ephemeral photo using its existing Telegram file ID",
ephemeralMessageParameters = EphemeralMessageParameters(receiverUserId),
receiverUserId = receiverUserId,
)
val ephemeralMessageId = (sent as? PossiblyEphemeralMessage)?.ephemeralMessageId
?: return@onCommand
@@ -180,7 +173,7 @@ suspend fun main(vararg args: String) {
chatId = livePhotoMessage.chat.id,
livePhoto = livePhoto,
text = "Ephemeral Live Photo using existing Telegram file IDs",
ephemeralMessageParameters = EphemeralMessageParameters(receiverUserId),
receiverUserId = receiverUserId,
)
val ephemeralMessageId = (sent as? PossiblyEphemeralMessage)?.ephemeralMessageId
?: return@onCommand
@@ -203,23 +196,19 @@ suspend fun main(vararg args: String) {
// Incoming ephemeral messages: detect them via PossiblyEphemeralMessage, then answer them.
onContentMessage { message ->
val ephemeral = (message as? PossiblyEphemeralMessage)?.takeIf { it.ephemeralMessageId != null }
val ephemeralMessageId = (message as? PossiblyEphemeralMessage)?.ephemeralMessageId
?: return@onContentMessage
val receiverUserId = message.ephemeralReplyReceiverUserIdOrNull ?: return@onContentMessage
// reply smart-branch: because `message` is ephemeral, this reply is sent ephemeral to the same
// receiver automatically — no ephemeral parameters needed here.
// reply derives the receiver and ephemeral message ID from the incoming message.
reply(message, "Got your ephemeral message — I am replying ephemerally too.")
// The explicit equivalent, addressing the ephemeral message by hand:
val receiverUserId = ephemeral.ephemeralReplyReceiverUserIdOrNull
if (receiverUserId != null) {
replyToEphemeral(
message.chat.id,
EphemeralMessageParameters(receiverUserId),
ephemeral.ephemeralMessageId!!,
"Explicit ephemeral reply via replyToEphemeral",
)
}
replyToEphemeral(
chatId = message.chat.id,
receiverUserId = receiverUserId,
ephemeralMessageId = ephemeralMessageId,
text = "Explicit ephemeral reply via replyToEphemeral",
)
}
setMyCommands(