mirror of
https://github.com/InsanusMokrassar/TelegramBotAPI-examples.git
synced 2026-11-27 22:03:07 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97b4391495 | ||
|
|
d0da6c851b | ||
|
|
030549fdb7 | ||
|
|
48b0e068d5 | ||
|
|
c0c5805705 | ||
|
|
f6882913b8 | ||
|
|
447de0c3ce | ||
|
|
3b7adc4033 |
No files matched your search
@@ -11,12 +11,12 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="{{$title}}Kt"
|
||||
{{$subtitle}}
|
||||
application.mainClass = "{{$title}}Kt"
|
||||
description = "{{$subtitle}}"
|
||||
|
||||
|
||||
dependencies {
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
|
||||
|
||||
implementation "dev.inmo:tgbotapi:$telegram_bot_api_version"
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="BoostsInfoKt"
|
||||
application.mainClass = "BoostsInfoKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="BotSubscriptionsBotKt"
|
||||
application.mainClass = "BotSubscriptionsBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -22,6 +22,7 @@ This is a feature demonstration, not a production-ready bot. Several commands ch
|
||||
| Edit bio (`can_edit_bio`) | `/set_business_account_bio` |
|
||||
| Edit profile photo (`can_edit_profile_photo`) | Both profile-photo commands |
|
||||
| View gifts and Stars (`can_view_gifts_and_stars`) | Balance and gift-list commands |
|
||||
| Convert gifts to Stars (`can_convert_gifts_to_stars`) | `/delete_business_account_gift` |
|
||||
| Transfer Stars (`can_transfer_stars`) | `/transfer_business_account_stars` |
|
||||
| Manage stories (`can_manage_stories`) | `/post_story` and `/delete_story` |
|
||||
|
||||
@@ -58,7 +59,7 @@ The inline **Read message** button calls `readBusinessMessage`. **Delete message
|
||||
|
||||
## Private-chat commands
|
||||
|
||||
These commands must be sent by the connected account owner in their private chat with the bot. Except for `/get_business_account_info`, handlers silently stop when that chat is not associated with an in-memory business connection.
|
||||
Send these commands from the connected account owner's private chat with the bot. The account-info and gift-deletion commands report a missing connection. The other commands require a connection already recorded in memory.
|
||||
|
||||
| Command | Behavior |
|
||||
| --- | --- |
|
||||
@@ -67,7 +68,8 @@ These commands must be sent by the connected account owner in their private chat
|
||||
| `/set_business_account_username <username>` | Changes the account username to the single supplied argument. |
|
||||
| `/get_business_account_star_balance` | Prints the account's current Telegram Stars balance. |
|
||||
| `/transfer_business_account_stars <count>` | Transfers an integer number of Stars from the business account to the bot. Telegram accepts values from 1 through 10,000; this example leaves range validation to Telegram. |
|
||||
| `/get_business_account_gifts` | Fetches every page of owned gifts and prints their Kotlin representations, splitting long output across messages. |
|
||||
| `/get_business_account_gifts` | Lists each gift with its owned gift ID when Telegram supplies one, followed by the full gift details. Long results span multiple messages. |
|
||||
| `/delete_business_account_gift <owned_gift_id>` | Permanently deletes the specified regular, unlimited, unrefunded gift. Type the command directly in the owner's bot chat using the owned gift ID from the listing. The bot checks the active connection, sender and business right before calling `deleteBusinessAccountGift`. Deletion credits no Stars. |
|
||||
| `/set_business_account_bio <text>` | Saves the current bio, sets the complete text after the command as the new bio, waits 15 seconds, and attempts to restore the saved value. An empty text clears it temporarily. |
|
||||
| `/set_business_account_profile_photo` | Reply to a photo with this command to set it as the main profile photo; after 15 seconds the bot removes that photo. |
|
||||
| `/set_business_account_profile_photo_public` | Reply to a photo to set it as the public profile photo; after 15 seconds the bot removes it. |
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="BusinessConnectionsBotKt"
|
||||
application.mainClass = "BusinessConnectionsBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -3,9 +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.common.Percentage
|
||||
import dev.inmo.tgbotapi.types.chat.PreviewBot
|
||||
import dev.inmo.tgbotapi.bot.exceptions.BotException
|
||||
import dev.inmo.tgbotapi.extensions.api.answers.answer
|
||||
import dev.inmo.tgbotapi.extensions.api.bot.getMe
|
||||
import dev.inmo.tgbotapi.extensions.api.business.deleteBusinessAccountGift
|
||||
import dev.inmo.tgbotapi.extensions.api.business.getBusinessAccountStarBalance
|
||||
import dev.inmo.tgbotapi.extensions.api.business.deleteBusinessMessages
|
||||
import dev.inmo.tgbotapi.extensions.api.business.getBusinessAccountGifts
|
||||
@@ -41,23 +42,28 @@ import dev.inmo.tgbotapi.extensions.utils.withContentOrNull
|
||||
import dev.inmo.tgbotapi.requests.abstracts.multipartFile
|
||||
import dev.inmo.tgbotapi.requests.business_connection.InputProfilePhoto
|
||||
import dev.inmo.tgbotapi.requests.stories.PostStory
|
||||
import dev.inmo.tgbotapi.types.AreaPosition
|
||||
import dev.inmo.tgbotapi.types.ChatId
|
||||
import dev.inmo.tgbotapi.types.GiftId
|
||||
import dev.inmo.tgbotapi.types.MessageId
|
||||
import dev.inmo.tgbotapi.types.RawChatId
|
||||
import dev.inmo.tgbotapi.types.business_connection.BusinessConnectionId
|
||||
import dev.inmo.tgbotapi.types.chat.PreviewBot
|
||||
import dev.inmo.tgbotapi.types.chat.PrivateChat
|
||||
import dev.inmo.tgbotapi.types.message.abstracts.ChatContentMessage
|
||||
import dev.inmo.tgbotapi.types.message.abstracts.FromUserMessage
|
||||
import dev.inmo.tgbotapi.types.message.content.LivePhotoContent
|
||||
import dev.inmo.tgbotapi.types.message.content.PhotoContent
|
||||
import dev.inmo.tgbotapi.types.message.content.StoryContent
|
||||
import dev.inmo.tgbotapi.types.message.content.TextContent
|
||||
import dev.inmo.tgbotapi.types.message.content.VideoContent
|
||||
import dev.inmo.tgbotapi.types.message.content.VisualMediaGroupPartContent
|
||||
import dev.inmo.tgbotapi.types.message.textsources.BotCommandTextSource
|
||||
import dev.inmo.tgbotapi.types.stories.InputStoryContent
|
||||
import dev.inmo.tgbotapi.types.stories.InputStoryContent.*
|
||||
import dev.inmo.tgbotapi.types.stories.StoryArea
|
||||
import dev.inmo.tgbotapi.types.stories.StoryAreaPosition
|
||||
import dev.inmo.tgbotapi.types.stories.StoryAreaType
|
||||
import dev.inmo.tgbotapi.types.toChatId
|
||||
import dev.inmo.tgbotapi.utils.botCommand
|
||||
import dev.inmo.tgbotapi.utils.code
|
||||
import dev.inmo.tgbotapi.utils.extensions.splitForText
|
||||
@@ -324,14 +330,51 @@ suspend fun main(args: Array<String>) {
|
||||
}
|
||||
} else {
|
||||
giftsFlow.collect { giftsPage ->
|
||||
giftsPage.gifts.joinToString {
|
||||
it.toString()
|
||||
giftsPage.gifts.joinToString("\n\n") { gift ->
|
||||
buildString {
|
||||
gift.ownedGiftId?.let { appendLine("Owned gift ID ${it.string}") }
|
||||
append(gift)
|
||||
}
|
||||
}.splitForText().forEach { message ->
|
||||
reply(it, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val deleteGiftCommand = "delete_business_account_gift"
|
||||
onCommandWithArgs(deleteGiftCommand, initialFilter = { message ->
|
||||
val command = message.content.textSources.firstOrNull() as? BotCommandTextSource
|
||||
message.chat is PrivateChat && message.forwardInfo == null && command?.command == deleteGiftCommand
|
||||
}) { message, arguments ->
|
||||
val ownedGiftId = arguments.singleOrNull()?.takeIf { it.isNotBlank() }
|
||||
if (ownedGiftId == null) {
|
||||
reply(message, "Use /$deleteGiftCommand <owned_gift_id> to permanently delete one gift.")
|
||||
return@onCommandWithArgs
|
||||
}
|
||||
val connectionId = businessConnectionsChatsMutex.withLock {
|
||||
chatsBusinessConnections[message.chat.id.toChatId()]
|
||||
}
|
||||
if (connectionId == null) {
|
||||
reply(message, "No business account is connected to this chat.")
|
||||
return@onCommandWithArgs
|
||||
}
|
||||
val result = try {
|
||||
val connection = getBusinessConnection(connectionId)
|
||||
when {
|
||||
!connection.isEnabled || connection.user.id != (message as? FromUserMessage)?.from?.id ->
|
||||
"Only the owner of an active business connection can delete a gift."
|
||||
!connection.rights.canConvertGiftsToStars ->
|
||||
"Grant the Convert gifts to Stars business right to delete a gift."
|
||||
else -> {
|
||||
deleteBusinessAccountGift(connectionId, GiftId(ownedGiftId))
|
||||
"Deleted owned gift $ownedGiftId."
|
||||
}
|
||||
}
|
||||
} catch (error: BotException) {
|
||||
error.response?.description ?: "Telegram could not delete this gift."
|
||||
}
|
||||
reply(message, result)
|
||||
}
|
||||
onCommand("set_business_account_bio", requireOnlyCommandInMessage = false, initialFilter = { it.chat is PrivateChat }) {
|
||||
val initialBio = getChat(it.chat).extendedPrivateChatOrThrow().bio
|
||||
val bio = it.content.text.removePrefix("/set_business_account_bio").trim()
|
||||
@@ -463,7 +506,7 @@ suspend fun main(args: Array<String>) {
|
||||
activePeriod = PostStory.ACTIVE_PERIOD_6_HOURS,
|
||||
areas = listOf(
|
||||
StoryArea(
|
||||
StoryAreaPosition(
|
||||
AreaPosition(
|
||||
x = Percentage.of100(50.0),
|
||||
y = Percentage.of100(50.0),
|
||||
width = Percentage.of100(8.0),
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="ChatAvatarSetterKt"
|
||||
application.mainClass = "ChatAvatarSetterKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="ChatManagementBotKt"
|
||||
application.mainClass = "ChatManagementBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="ChecklistsBotKt"
|
||||
application.mainClass = "ChecklistsBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# CommunitiesBot
|
||||
|
||||
This long-polling example demonstrates Communities support introduced in Telegram Bot API 10.2: typed service events when a chat joins or leaves a community, and inspection of a chat's current community.
|
||||
This long-polling example demonstrates Communities support introduced in Telegram Bot API 10.2 and extended in 10.3: typed service events when a chat joins or leaves a community, an event when a user joins a chat from a community, and inspection of a chat's current community.
|
||||
|
||||
## Behavior, commands, and triggers
|
||||
|
||||
@@ -10,18 +10,21 @@ At startup, the bot calls `getMe` and prints its bot information. It also prints
|
||||
| --- | --- |
|
||||
| `community_chat_added` service message | `onCommunityChatAdded` logs the chat and community name/ID, sends a join notice, then calls `getChat` and logs its nullable `community`. |
|
||||
| `community_chat_removed` service message | `onCommunityChatRemoved` logs the chat and sends a leave notice. This event is fieldless, so it has no former-community details. |
|
||||
| `community_chat_joined` service message | `onCommunityChatJoined` logs the source community and replies with a welcome message. This means a user joined the current chat from a community; it is distinct from adding the chat itself to a community. |
|
||||
| `/community` | Calls `getChat` and replies with the current community name/ID, or says the chat is not in a community. |
|
||||
| `/wait_community_added` | Waits without a timeout for the next added event in the command's chat, then replies with the community name/ID. |
|
||||
| `/wait_community_removed` | Waits without a timeout for the next removed event in the command's chat, then replies with the chat ID. Its initial waiting reply currently says "added." |
|
||||
| `/wait_community_removed` | Waits without a timeout for the next removed event in the command's chat, then replies with the chat ID. |
|
||||
| `/wait_community_joined` | Waits without a timeout for the next user-from-community join event in the command's chat, then replies with the source community name/ID. |
|
||||
|
||||
Commands use no positional arguments; other commands only appear in the generic update log. Each wait first sends a waiting reply, filters events with `sameChat`, and takes the first match.
|
||||
|
||||
## API concepts
|
||||
|
||||
- `CommunityChatAdded` carries a `Community` with a `CommunityId` and name; `CommunityChatRemoved` carries no fields.
|
||||
- `onCommunityChatAdded` and `onCommunityChatRemoved` provide typed handlers for the service events.
|
||||
- `CommunityChatJoined` carries the community through which a user joined the current chat.
|
||||
- `onCommunityChatAdded`, `onCommunityChatRemoved`, and `onCommunityChatJoined` provide typed handlers for the service events.
|
||||
- `getChat(...).community` exposes the nullable community on `ExtendedChat` without a subtype cast.
|
||||
- `waitCommunityChatAddedEventsMessages` and `waitCommunityChatRemovedEventsMessages` expose typed event-message flows.
|
||||
- `waitCommunityChatAddedEventsMessages`, `waitCommunityChatRemovedEventsMessages`, and `waitCommunityChatJoinedEventsMessages` expose typed event-message flows.
|
||||
|
||||
## Telegram setup and permissions
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="CommunitiesBotKt"
|
||||
application.mainClass = "CommunitiesBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -7,13 +7,13 @@ import dev.inmo.tgbotapi.extensions.api.bot.getMe
|
||||
import dev.inmo.tgbotapi.extensions.api.chat.get.getChat
|
||||
import dev.inmo.tgbotapi.extensions.api.send.reply
|
||||
import dev.inmo.tgbotapi.extensions.api.send.send
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitCommunityChatAdded
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitCommunityChatAddedEventsMessages
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitCommunityChatRemoved
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitCommunityChatJoinedEventsMessages
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitCommunityChatRemovedEventsMessages
|
||||
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.onCommunityChatAdded
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommunityChatJoined
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommunityChatRemoved
|
||||
import dev.inmo.tgbotapi.extensions.utils.extensions.sameChat
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
@@ -25,10 +25,11 @@ import kotlinx.coroutines.flow.first
|
||||
* Starts a long-polling bot that demonstrates Telegram Communities.
|
||||
*
|
||||
* [onCommunityChatAdded] receives the joined [dev.inmo.tgbotapi.types.communities.Community], while
|
||||
* [onCommunityChatRemoved] receives a fieldless removal event. `/community` reads
|
||||
* [dev.inmo.tgbotapi.types.chat.ExtendedChat.community] with [getChat]. The two wait commands use
|
||||
* [waitCommunityChatAddedEventsMessages] and [waitCommunityChatRemovedEventsMessages] to take the first same-chat
|
||||
* event without a timeout. The bot prints its [getMe] result and every received update.
|
||||
* [onCommunityChatRemoved] receives a fieldless removal event, while [onCommunityChatJoined] reports a user joining
|
||||
* the chat from a community. `/community` reads
|
||||
* [dev.inmo.tgbotapi.types.chat.ExtendedChat.community] with [getChat]. The three wait commands use typed event-message
|
||||
* expectations to take the first same-chat event without a timeout. The bot prints its [getMe] result and every
|
||||
* received update.
|
||||
*
|
||||
* @param args the bot token followed by the optional, case-sensitive `debug` and `testServer` flags; unknown trailing
|
||||
* arguments are ignored
|
||||
@@ -72,6 +73,13 @@ suspend fun main(vararg args: String) {
|
||||
send(message.chat.id, "This chat has left its community")
|
||||
}
|
||||
|
||||
// community_chat_joined: a user joined this chat through a community
|
||||
onCommunityChatJoined { message ->
|
||||
val community = message.chatEvent.community
|
||||
println("A user joined chat ${message.chat.id} from community '${community.name}' (id=${community.id.long})")
|
||||
reply(message, "Welcome! You joined from the ${community.name} community.")
|
||||
}
|
||||
|
||||
// Inspect the current chat's community on demand
|
||||
onCommand("community") {
|
||||
val community = getChat(it.chat.id).community
|
||||
@@ -94,11 +102,18 @@ suspend fun main(vararg args: String) {
|
||||
|
||||
// Suspend until the next community-removed event message from this chat.
|
||||
onCommand("wait_community_removed") { origin ->
|
||||
reply(origin, "Waiting for this chat to be added to a community...")
|
||||
reply(origin, "Waiting for this chat to be removed from a community...")
|
||||
waitCommunityChatRemovedEventsMessages().filter { it.sameChat(origin) }.first()
|
||||
reply(origin, "Chat removed from its community (${origin.chat.id})")
|
||||
}
|
||||
|
||||
// Suspend until a user joins this chat from a community.
|
||||
onCommand("wait_community_joined") { origin ->
|
||||
reply(origin, "Waiting for somebody to join this chat from a community...")
|
||||
val event = waitCommunityChatJoinedEventsMessages().filter { it.sameChat(origin) }.first().chatEvent
|
||||
reply(origin, "A user joined from ${event.community.name} (id=${event.community.id.long})")
|
||||
}
|
||||
|
||||
allUpdatesFlow.subscribeSafelyWithoutExceptions(this) {
|
||||
println(it)
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="CustomBotKt"
|
||||
application.mainClass = "CustomBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -8,6 +8,11 @@ ways to consume their payloads with the TelegramBotAPI behaviour builder.
|
||||
- On startup, the bot fetches and prints its own account details. It stops if the
|
||||
account has no username, because a username is required to build a deep link.
|
||||
- `/start` without arguments returns a short usage hint.
|
||||
- `/invite` returns the bot owner's invitation link. The owner can open it to invite a user to
|
||||
a private chat with the bot. When Telegram delivers `WriteAccessAllowed.FromInvitation`,
|
||||
the bot greets that user and names the inviter.
|
||||
- `/sharetheme` shows the theme for sharing a link to the current chat. For an emoji theme it
|
||||
looks up the selected backdrop by ID. For a unique-gift theme it shows the gift name.
|
||||
- A text message containing no bot-command entity is used as the payload of a new
|
||||
deep link, which the bot returns to the sender.
|
||||
- A `/start <payload>` deep link is observed by both an `onDeepLink` trigger and a
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="DeepLinksBotKt"
|
||||
application.mainClass = "DeepLinksBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import dev.inmo.micro_utils.coroutines.subscribeLoggingDropExceptions
|
||||
import dev.inmo.tgbotapi.extensions.api.bot.getMe
|
||||
import dev.inmo.tgbotapi.extensions.api.chat.get.getChat
|
||||
import dev.inmo.tgbotapi.extensions.api.chat.get.getChatShareThemeBackdrops
|
||||
import dev.inmo.tgbotapi.extensions.api.send.reply
|
||||
import dev.inmo.tgbotapi.extensions.api.send.sendMessage
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitDeepLinks
|
||||
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.onDeepLink
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onText
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onWriteAccessAllowed
|
||||
import dev.inmo.tgbotapi.extensions.utils.formatting.makeBotInviteLink
|
||||
import dev.inmo.tgbotapi.extensions.utils.formatting.makeTelegramDeepLink
|
||||
import dev.inmo.tgbotapi.types.EmojiType
|
||||
import dev.inmo.tgbotapi.types.chat.ChatShareTheme
|
||||
import dev.inmo.tgbotapi.types.message.ChatEvents.forum.WriteAccessAllowed
|
||||
import dev.inmo.tgbotapi.types.message.textsources.BotCommandTextSource
|
||||
|
||||
/**
|
||||
@@ -40,6 +48,32 @@ suspend fun main(vararg args: String) {
|
||||
onCommand("start", requireOnlyCommandInMessage = true) { // handling of `start` without args
|
||||
reply(it, "Hi :) Send me any text and I will try hard to create deeplink for you")
|
||||
}
|
||||
onCommand("invite") {
|
||||
reply(it, makeBotInviteLink(username))
|
||||
}
|
||||
onWriteAccessAllowed { message ->
|
||||
val invitation = message.chatEvent as? WriteAccessAllowed.FromInvitation ?: return@onWriteAccessAllowed
|
||||
sendMessage(message.chat, "You were invited by ${invitation.inviter.firstName}.")
|
||||
}
|
||||
onCommand("sharetheme") { message ->
|
||||
val description = when (val theme = getChat(message.chat.id).shareTheme) {
|
||||
is ChatShareTheme.Emoji -> {
|
||||
val emojis = theme.emojis.joinToString(" ") {
|
||||
when (it) {
|
||||
is EmojiType.Emoji -> it.emoji
|
||||
is EmojiType.CustomEmoji -> "custom emoji ${it.customEmojiId.string}"
|
||||
}
|
||||
}
|
||||
val backdrop = theme.backgroundBackdropId?.let { id ->
|
||||
getChatShareThemeBackdrops().backdrops.firstOrNull { it.id == id }?.name ?: id.int.toString()
|
||||
}
|
||||
"Emoji: $emojis\nBackdrop: ${backdrop ?: "default"}"
|
||||
}
|
||||
is ChatShareTheme.UniqueGift -> "Unique gift: ${theme.gift.name.value}"
|
||||
null -> "This chat has no share theme."
|
||||
}
|
||||
reply(message, description)
|
||||
}
|
||||
onDeepLink { (it, deepLink) ->
|
||||
reply(it, "Ok, I got deep link \"${deepLink}\" in trigger")
|
||||
}
|
||||
|
||||
+23
-10
@@ -2,7 +2,8 @@
|
||||
|
||||
DraftsBot demonstrates streaming a message draft before sending the finished
|
||||
message. It receives updates through long polling and uses the same built-in
|
||||
Lorem ipsum text for both examples.
|
||||
Lorem ipsum text for all examples. Bot API 10.3's stoppable generation controls
|
||||
and `stopped_message_generation` updates are included.
|
||||
|
||||
## Commands
|
||||
|
||||
@@ -10,18 +11,32 @@ Lorem ipsum text for both examples.
|
||||
500 ms, then sends the complete text as a normal message.
|
||||
- `/test_empty_draft` first publishes an empty draft, waits 1.5 seconds, streams
|
||||
the same prefixes, and then sends the complete text.
|
||||
- `/test_stoppable_draft` continuously streams progressively longer revisions
|
||||
with `canStop = true` and `keepOnStop = true`. Telegram displays a stop control;
|
||||
stopping keeps the most recent draft revision and causes the flow helper to
|
||||
return `false`. Before streaming, the handler subscribes to
|
||||
`waitMessageGenerationStopped` and filters the expectation by chat and draft
|
||||
ID, then logs the matched stop event. It deliberately sends no confirmation
|
||||
message, because sending one would immediately remove the draft retained by
|
||||
`keepOnStop`. If streaming ends because of another request failure and no
|
||||
matching update arrives within five seconds, the bot logs that distinction
|
||||
instead of waiting forever.
|
||||
|
||||
The bot advertises both commands in Telegram's command menu for all group chats.
|
||||
The handlers themselves are not restricted by chat type, so either command can
|
||||
also be entered manually in a private chat.
|
||||
The bot advertises all three commands in Telegram's command menu for private
|
||||
chats and filters each handler to private chats, as required by Telegram's draft
|
||||
methods.
|
||||
|
||||
The typed `onMessageGenerationStopped` handler logs the chat, optional topic ID,
|
||||
and draft ID from every generation-stopped update, independently of the scoped
|
||||
expectation used by `/test_stoppable_draft`. Both apply to text and rich-message
|
||||
drafts sent by this bot token.
|
||||
|
||||
## Setup
|
||||
|
||||
1. Obtain a bot token and keep it out of source control.
|
||||
2. Start a private chat with the bot, or add it to a group where you want to run
|
||||
the example.
|
||||
3. In groups, allow the bot to send messages. No administrator rights are
|
||||
otherwise required by this example.
|
||||
2. Start a private chat with the bot. Telegram doesn't accept a group or channel
|
||||
ID for `sendMessageDraft`.
|
||||
3. No administrator rights are required by this example.
|
||||
|
||||
The first program argument is required and must be the bot token. Omitting it
|
||||
causes startup to fail; any later arguments are ignored.
|
||||
@@ -34,8 +49,6 @@ From the repository root, run:
|
||||
./gradlew :DraftsBot:run --args="<BOT_TOKEN>"
|
||||
```
|
||||
|
||||
> **Known issue:** `DraftsBot/build.gradle` currently declares `TopicsHandlingKt` as the main class, while this bot's entry point is `DraftsBotKt`. The `run` task cannot start until that Gradle setting is corrected; it is left unchanged by this documentation-only update.
|
||||
|
||||
Every received update is printed to standard output. Unhandled polling errors
|
||||
are printed with their stack traces, and HTTP request, socket, and connection
|
||||
timeouts are each configured to 30 seconds.
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="TopicsHandlingKt"
|
||||
application.mainClass = "DraftsBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -12,7 +12,9 @@ import dev.inmo.tgbotapi.extensions.api.send.send
|
||||
import dev.inmo.tgbotapi.extensions.api.send.sendMessageDraftFlow
|
||||
import dev.inmo.tgbotapi.extensions.api.send.sendMessageDraftFlowWithTexts
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.telegramBotWithBehaviourAndLongPolling
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitMessageGenerationStopped
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommand
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onMessageGenerationStopped
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onForumTopicClosed
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onForumTopicCreated
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onForumTopicEdited
|
||||
@@ -30,18 +32,26 @@ import dev.inmo.tgbotapi.types.BotCommand
|
||||
import dev.inmo.tgbotapi.types.ForumTopic
|
||||
import dev.inmo.tgbotapi.types.chat.PrivateChat
|
||||
import dev.inmo.tgbotapi.types.commands.BotCommandScope
|
||||
import dev.inmo.tgbotapi.utils.DraftIdAllocator
|
||||
import io.ktor.client.plugins.*
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.filter
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
/** Sample text streamed as a draft and then sent as the completed message. */
|
||||
const val testText = """
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
|
||||
"""
|
||||
|
||||
private val stoppableDraftIds = DraftIdAllocator()
|
||||
|
||||
/**
|
||||
* Starts DraftsBot with long polling and registers the draft demonstration commands.
|
||||
*
|
||||
@@ -67,7 +77,7 @@ suspend fun main(vararg args: String) {
|
||||
}
|
||||
}
|
||||
) {
|
||||
onCommand("test_draft_flow") {
|
||||
onCommand("test_draft_flow", initialFilter = { it.chat is PrivateChat }) {
|
||||
sendMessageDraftFlowWithTexts(
|
||||
it.chat.id,
|
||||
flow<String> {
|
||||
@@ -85,7 +95,7 @@ suspend fun main(vararg args: String) {
|
||||
|
||||
// sendMessageDraft now accepts empty text (length 0 is valid since TG Bot API 9.0)
|
||||
// Useful to show a typing indicator without any text yet
|
||||
onCommand("test_empty_draft") {
|
||||
onCommand("test_empty_draft", initialFilter = { it.chat is PrivateChat }) {
|
||||
sendMessageDraftFlowWithTexts(
|
||||
it.chat.id,
|
||||
flow<String> {
|
||||
@@ -103,10 +113,62 @@ suspend fun main(vararg args: String) {
|
||||
send(it.chat, testText)
|
||||
}
|
||||
|
||||
// Bot API 10.3 lets the user stop generation. The expectation is subscribed before streaming starts so it
|
||||
// cannot miss a fast stop update; matching both chat and draft ID also avoids consuming another draft's event.
|
||||
onCommand("test_stoppable_draft", initialFilter = { it.chat is PrivateChat }) { origin ->
|
||||
val draftId = stoppableDraftIds.allocate()
|
||||
val stoppedUpdate = async(start = CoroutineStart.UNDISPATCHED) {
|
||||
waitMessageGenerationStopped()
|
||||
.filter { it.chat.id == origin.chat.id && it.draftId == draftId }
|
||||
.first()
|
||||
}
|
||||
try {
|
||||
val completed = sendMessageDraftFlowWithTexts(
|
||||
origin.chat.id,
|
||||
flow<String> {
|
||||
val step = 20
|
||||
var currentLength = step
|
||||
while (isActive) {
|
||||
delay(500L)
|
||||
emit(testText.take(currentLength.coerceAtMost(testText.length)))
|
||||
currentLength = (currentLength + step).coerceAtMost(testText.length)
|
||||
}
|
||||
},
|
||||
draftId = draftId,
|
||||
canStop = true,
|
||||
keepOnStop = true,
|
||||
)
|
||||
if (!completed) {
|
||||
val stopped = withTimeoutOrNull(5_000L) { stoppedUpdate.await() }
|
||||
if (stopped == null) {
|
||||
println("Draft streaming ended without a matching stopped_message_generation update")
|
||||
} else {
|
||||
// A normal message here would immediately remove the kept draft, so report only to stdout.
|
||||
println(
|
||||
"Expectation matched stopped draft ${stopped.draftId.long} in ${stopped.chat.id}; " +
|
||||
"Telegram kept its last revision temporarily."
|
||||
)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
stoppedUpdate.cancel()
|
||||
stoppableDraftIds.free(draftId)
|
||||
}
|
||||
}
|
||||
|
||||
// The stopped_message_generation update includes the chat, optional topic and stopped draft ID.
|
||||
onMessageGenerationStopped { stopped ->
|
||||
println(
|
||||
"Message generation stopped in ${stopped.chat.id}; " +
|
||||
"thread=${stopped.messageThreadId}, draft=${stopped.draftId}"
|
||||
)
|
||||
}
|
||||
|
||||
setMyCommands(
|
||||
BotCommand("test_draft_flow", "Start draft testing with flow"),
|
||||
BotCommand("test_empty_draft", "Draft starting from empty text (TG Bot API 9.0)"),
|
||||
scope = BotCommandScope.AllGroupChats
|
||||
BotCommand("test_stoppable_draft", "Stream a draft that the user can stop"),
|
||||
scope = BotCommandScope.AllPrivateChats
|
||||
)
|
||||
allUpdatesFlow.subscribeLoggingDropExceptions(this) {
|
||||
println(it)
|
||||
|
||||
@@ -1,22 +1,33 @@
|
||||
# EphemeralMessagesBot
|
||||
|
||||
Demonstrates 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) sends a personal message visible only to the user who
|
||||
pressed it. After three seconds the bot edits the message, then deletes it three seconds later.
|
||||
- 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.
|
||||
- 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 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.
|
||||
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
|
||||
|
||||
@@ -30,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:
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="EphemeralMessagesBotKt"
|
||||
application.mainClass = "EphemeralMessagesBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -3,32 +3,50 @@ 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.text.editEphemeralMessageText
|
||||
import dev.inmo.tgbotapi.extensions.api.edit.caption.editEphemeralMessageCaption
|
||||
import dev.inmo.tgbotapi.extensions.api.edit.media.editEphemeralMessageMedia
|
||||
import dev.inmo.tgbotapi.extensions.api.edit.text.editEphemeralMessageRichText
|
||||
import dev.inmo.tgbotapi.extensions.api.files.downloadFile
|
||||
import dev.inmo.tgbotapi.extensions.api.send.reply
|
||||
import dev.inmo.tgbotapi.extensions.api.send.replyToEphemeral
|
||||
import dev.inmo.tgbotapi.extensions.api.send.sendTextMessage
|
||||
import dev.inmo.tgbotapi.extensions.api.send.sendRichMessage
|
||||
import dev.inmo.tgbotapi.extensions.api.send.media.sendLivePhoto
|
||||
import dev.inmo.tgbotapi.extensions.api.send.media.sendPhoto
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitLivePhotoMessage
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitPhotoMessage
|
||||
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.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
|
||||
|
||||
/**
|
||||
* Runs the ephemeral-messages example bot using long polling.
|
||||
*
|
||||
* `/ephemeral` posts an inline button whose callback sends, edits, and deletes a message visible only to
|
||||
* the user who pressed it. Incoming [PossiblyEphemeralMessage] instances receive both an automatic
|
||||
* `/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
|
||||
* ephemeral [reply] and an explicit [replyToEphemeral].
|
||||
*
|
||||
* [args] must start with the bot token. The optional exact values `debug` and `testServer` respectively
|
||||
@@ -53,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")
|
||||
|
||||
@@ -68,57 +90,132 @@ suspend fun main(vararg args: String) {
|
||||
)
|
||||
}
|
||||
|
||||
// Send an ephemeral message in response to a callback query. `receiverUserId` + `callbackQueryId`
|
||||
// make the outgoing message ephemeral — Telegram shows it only to the querying user (and this also
|
||||
// serves as the answer to the callback query).
|
||||
onMessageDataCallbackQuery(Regex("reveal")) { query ->
|
||||
val chatId = query.message.chat.id
|
||||
val receiverUserId = query.from.id
|
||||
|
||||
val sent = sendTextMessage(
|
||||
chatId,
|
||||
"🔒 ${query.from.firstName}, here is your personal secret: 42",
|
||||
receiverUserId = receiverUserId,
|
||||
// Telegram resolves the destination from the callback, including callbacks carrying an inline message ID.
|
||||
onDataCallbackQuery("reveal") { query ->
|
||||
val sent = sendRichMessage(
|
||||
callbackQueryId = query.id,
|
||||
richMessage = InputRichMessageBlocks {
|
||||
paragraph {
|
||||
plain("🔒 ${query.from.firstName}, here is your personal secret: ")
|
||||
code("42")
|
||||
}
|
||||
},
|
||||
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: address the ephemeral message by chatId + receiverUserId + ephemeralMessageId
|
||||
editEphemeralMessageText(chatId, receiverUserId, ephemeralMessageId, "🔓 Revealed: the answer is 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.
|
||||
onCommand("ephemeral_photo") { origin ->
|
||||
val receiverUserId = origin.fromUserMessageOrNull()?.user?.id ?: return@onCommand
|
||||
reply(origin, "Send a photo. I will return it as ephemeral media and then re-upload it in an edit.")
|
||||
val photoMessage = waitPhotoMessage().filter {
|
||||
it.sameChat(origin) && it.fromUserMessageOrNull()?.user?.id == receiverUserId
|
||||
}.first()
|
||||
|
||||
val sent = sendPhoto(
|
||||
photoMessage.chat.id,
|
||||
photoMessage.content.media.fileId,
|
||||
text = "Ephemeral photo using its existing Telegram file ID",
|
||||
receiverUserId = receiverUserId,
|
||||
)
|
||||
val ephemeralMessageId = (sent as? PossiblyEphemeralMessage)?.ephemeralMessageId
|
||||
?: return@onCommand
|
||||
|
||||
val photoBytes = downloadFile(photoMessage.content)
|
||||
editEphemeralMessageMedia(
|
||||
photoMessage.chat.id,
|
||||
receiverUserId,
|
||||
ephemeralMessageId,
|
||||
TelegramMediaPhoto(
|
||||
photoBytes.asMultipartFile("ephemeral-photo.jpg"),
|
||||
text = "sample"
|
||||
),
|
||||
)
|
||||
editEphemeralMessageCaption(
|
||||
photoMessage.chat.id,
|
||||
receiverUserId,
|
||||
ephemeralMessageId,
|
||||
caption = "This caption is above newly uploaded media",
|
||||
showCaptionAboveMedia = true,
|
||||
)
|
||||
}
|
||||
|
||||
// A Live Photo has a main file plus a secondary `photo` file. ktgbotapi 37.0.0 includes both multipart
|
||||
// attachments when EditEphemeralMessageMedia builds its request.
|
||||
onCommand("ephemeral_live_photo") { origin ->
|
||||
val receiverUserId = origin.fromUserMessageOrNull()?.user?.id ?: return@onCommand
|
||||
reply(origin, "Send a Live Photo. I will send it ephemerally and edit it using two new uploads.")
|
||||
val livePhotoMessage = waitLivePhotoMessage().filter {
|
||||
it.sameChat(origin) && it.fromUserMessageOrNull()?.user?.id == receiverUserId
|
||||
}.first()
|
||||
val livePhoto = livePhotoMessage.content.media
|
||||
|
||||
val sent = sendLivePhoto(
|
||||
chatId = livePhotoMessage.chat.id,
|
||||
livePhoto = livePhoto,
|
||||
text = "Ephemeral Live Photo using existing Telegram file IDs",
|
||||
receiverUserId = receiverUserId,
|
||||
)
|
||||
val ephemeralMessageId = (sent as? PossiblyEphemeralMessage)?.ephemeralMessageId
|
||||
?: return@onCommand
|
||||
|
||||
val livePhotoBytes = downloadFile(livePhoto)
|
||||
val coverPhotoBytes = livePhoto.photo?.let { downloadFile(it) }
|
||||
editEphemeralMessageMedia(
|
||||
livePhotoMessage.chat.id,
|
||||
receiverUserId,
|
||||
ephemeralMessageId,
|
||||
TelegramMediaLivePhoto(
|
||||
file = livePhotoBytes.asMultipartFile("ephemeral-live-photo.mp4"),
|
||||
photo = coverPhotoBytes?.asMultipartFile("ephemeral-live-photo-cover.jpg")
|
||||
?: livePhoto.photo?.fileId
|
||||
?: livePhoto.fileId,
|
||||
text = "Edited with newly uploaded main and cover files",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// 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,
|
||||
receiverUserId,
|
||||
ephemeral.ephemeralMessageId!!,
|
||||
"Explicit ephemeral reply via replyToEphemeral",
|
||||
)
|
||||
}
|
||||
replyToEphemeral(
|
||||
chatId = message.chat.id,
|
||||
receiverUserId = receiverUserId,
|
||||
ephemeralMessageId = ephemeralMessageId,
|
||||
text = "Explicit ephemeral reply via replyToEphemeral",
|
||||
)
|
||||
}
|
||||
|
||||
setMyCommands(
|
||||
// isEphemeral marks a command whose response is an ephemeral (personal) message
|
||||
BotCommand("ephemeral", "Post a button that reveals an ephemeral (personal) message", isEphemeral = true),
|
||||
BotCommand("ephemeral_photo", "Re-upload a photo through an ephemeral media edit", isEphemeral = true),
|
||||
BotCommand("ephemeral_live_photo", "Re-upload both files of an ephemeral Live Photo", isEphemeral = true),
|
||||
)
|
||||
|
||||
allUpdatesFlow.subscribeSafelyWithoutExceptions(this) {
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="SimpleFSMBotKt"
|
||||
application.mainClass = "SimpleFSMBotKt"
|
||||
|
||||
repositories {
|
||||
mavenLocal()
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="FilesLoaderBotKt"
|
||||
application.mainClass = "FilesLoaderBotKt"
|
||||
|
||||
dependencies {
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="ForwardInfoSenderBotKt"
|
||||
application.mainClass = "ForwardInfoSenderBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
+12
-5
@@ -1,6 +1,6 @@
|
||||
# GiftsBot
|
||||
|
||||
Demonstrates the paginated owned-gift APIs by listing gifts for the chat in which the command is received.
|
||||
Lists gifts owned by the current chat and looks up individual collectible gifts by name.
|
||||
|
||||
## Behavior
|
||||
|
||||
@@ -15,12 +15,19 @@ Regular gifts are shown with their ID, optional text, and Stars cost. Unique gif
|
||||
name, model, and number. Long results are split into multiple Telegram messages; an empty result produces
|
||||
`This chat have no any gifts`.
|
||||
|
||||
## Command
|
||||
The bot also handles `UniqueGiftInfo` service messages with `onUniqueGiftSentOrReceived`. It logs and replies with
|
||||
Bot API 10.3's `text`, parsed `textSources` (`entities`), and `isPrivate` fields. When entities are present, the reply
|
||||
reuses them so the gift text keeps its formatting.
|
||||
|
||||
## Commands
|
||||
|
||||
- `/start` — lists the owned gifts selected by the current chat type. It must be the only command in the message and
|
||||
takes no arguments.
|
||||
- `/unique_gift <name>` calls `getUniqueGift` and replies with the collectible's number, model, symbol, backdrop,
|
||||
and Telegram link. Use the name after `t.me/nft/` in a collectible's link, or copy the name from a `/start` result.
|
||||
The lookup works independently of gift ownership.
|
||||
|
||||
Other commands and non-command messages are ignored.
|
||||
Other commands and ordinary non-command messages are ignored; unique-gift service messages are handled separately.
|
||||
|
||||
## Setup and permissions
|
||||
|
||||
@@ -30,8 +37,8 @@ Other commands and non-command messages are ignored.
|
||||
4. For business-chat use, enable the bot's Business/Secretary mode, connect it to the business account, and grant the
|
||||
**View gifts and Stars** (`can_view_gifts_and_stars`) business right.
|
||||
|
||||
The example performs no access checks or error recovery, so Telegram API or permission errors end that command
|
||||
handler.
|
||||
The lookup reports Telegram's error description when available. The owned-gift listing requires the applicable chat
|
||||
or business access.
|
||||
|
||||
## Arguments and launch
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="GiftsBotKt"
|
||||
application.mainClass = "GiftsBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -2,35 +2,38 @@ import dev.inmo.kslog.common.KSLog
|
||||
import dev.inmo.kslog.common.LogLevel
|
||||
import dev.inmo.kslog.common.defaultMessageFormatter
|
||||
import dev.inmo.kslog.common.setDefaultKSLog
|
||||
import dev.inmo.tgbotapi.bot.exceptions.BotException
|
||||
import dev.inmo.tgbotapi.extensions.api.bot.getMe
|
||||
import dev.inmo.tgbotapi.extensions.api.business.getBusinessAccountGiftsFlow
|
||||
import dev.inmo.tgbotapi.extensions.api.gifts.getChatGiftsFlow
|
||||
import dev.inmo.tgbotapi.extensions.api.gifts.getUniqueGift
|
||||
import dev.inmo.tgbotapi.extensions.api.gifts.getUserGiftsFlow
|
||||
import dev.inmo.tgbotapi.extensions.api.send.reply
|
||||
import dev.inmo.tgbotapi.extensions.api.send.withTypingAction
|
||||
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.onGiveawayCompleted
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onGiveawayContent
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onGiveawayCreated
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onGiveawayWinners
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommandWithArgs
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onUniqueGiftSentOrReceived
|
||||
import dev.inmo.tgbotapi.types.chat.BusinessChat
|
||||
import dev.inmo.tgbotapi.types.chat.PrivateChat
|
||||
import dev.inmo.tgbotapi.types.chat.PublicChat
|
||||
import dev.inmo.tgbotapi.types.chat.UnknownChatType
|
||||
import dev.inmo.tgbotapi.types.gifts.OwnedGift
|
||||
import dev.inmo.tgbotapi.types.gifts.UniqueGiftName
|
||||
import dev.inmo.tgbotapi.types.message.textsources.splitForText
|
||||
import dev.inmo.tgbotapi.utils.bold
|
||||
import dev.inmo.tgbotapi.utils.buildEntities
|
||||
import dev.inmo.tgbotapi.utils.regular
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
|
||||
/**
|
||||
* Starts a long-polling bot whose standalone `/start` command lists all owned gifts for the current chat.
|
||||
* Lists owned gifts with `/start` and looks up an individual collectible by name with `/unique_gift`.
|
||||
*
|
||||
* Business chats are queried through their business connection, private chats through their user ID, and public or
|
||||
* unknown chat types through their chat ID. Regular and unique gifts are rendered as formatted text and long results
|
||||
* are split across replies. The bot also prints its [getMe] result at startup.
|
||||
* are split across replies. Unique-gift service messages also expose the Bot API 10.3 text, entities and privacy flag.
|
||||
* The bot prints its [getMe] result at startup.
|
||||
*
|
||||
* @param args the bot token followed by optional, case-sensitive `debug` and `testServer` flags; unknown trailing
|
||||
* arguments are ignored
|
||||
@@ -55,6 +58,48 @@ suspend fun main(vararg args: String) {
|
||||
val me = getMe()
|
||||
println(me)
|
||||
|
||||
onCommandWithArgs("unique_gift") { message, arguments ->
|
||||
val name = arguments.singleOrNull()?.takeIf { it.isNotBlank() }
|
||||
if (name == null) {
|
||||
reply(message, "Use /unique_gift <name> with the name from a t.me/nft/ link.")
|
||||
return@onCommandWithArgs
|
||||
}
|
||||
val gift = try {
|
||||
getUniqueGift(UniqueGiftName(name))
|
||||
} catch (error: BotException) {
|
||||
reply(message, error.response?.description ?: "Telegram could not look up this gift.")
|
||||
return@onCommandWithArgs
|
||||
}
|
||||
reply(
|
||||
message,
|
||||
"${gift.baseName} #${gift.number}\n" +
|
||||
"${gift.model.name} model, ${gift.symbol.name} symbol, ${gift.backdrop.name} backdrop\n" +
|
||||
gift.name.nftLink
|
||||
)
|
||||
}
|
||||
|
||||
onUniqueGiftSentOrReceived { message ->
|
||||
val uniqueGiftInfo = message.chatEvent
|
||||
println(
|
||||
"Unique gift ${uniqueGiftInfo.gift.name.value}: " +
|
||||
"text=${uniqueGiftInfo.text}, textSources=${uniqueGiftInfo.textSources}, " +
|
||||
"isPrivate=${uniqueGiftInfo.isPrivate}"
|
||||
)
|
||||
reply(
|
||||
message,
|
||||
buildEntities {
|
||||
bold("Unique gift") + ": ${uniqueGiftInfo.gift.name.value}\n"
|
||||
bold("Private") + ": ${uniqueGiftInfo.isPrivate}\n"
|
||||
bold("Text") + ": "
|
||||
if (uniqueGiftInfo.textSources.isEmpty()) {
|
||||
regular(uniqueGiftInfo.text ?: "(None)")
|
||||
} else {
|
||||
+uniqueGiftInfo.textSources
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
onCommand("start") {
|
||||
val giftsFlow = when (val chat = it.chat) {
|
||||
is BusinessChat -> {
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="GiveawaysBotKt"
|
||||
application.mainClass = "GiveawaysBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="GuestQueryBotKt"
|
||||
application.mainClass = "GuestQueryBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
+2
-3
@@ -5,9 +5,8 @@ message addresses the bot by username.
|
||||
|
||||
## Trigger and replies
|
||||
|
||||
There are no slash commands. The bot handles a content message only when its
|
||||
text contains the bot's full username. This is a case-sensitive substring
|
||||
check; messages without text or without the username are ignored.
|
||||
The bot greets messages whose text contains its primary username or an active alias
|
||||
returned by `getMe`. The match includes the leading `@` and ignores case.
|
||||
|
||||
- In a private chat, it replies with a MarkdownV2 text mention of the user.
|
||||
- In a group or supergroup, it greets the group and links its title to a public
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="HelloBotKt"
|
||||
application.mainClass = "HelloBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -32,8 +32,11 @@ suspend fun main(vararg args: String) {
|
||||
|
||||
telegramBotWithBehaviourAndLongPolling(botToken, CoroutineScope(Dispatchers.IO)) {
|
||||
val me = getMe()
|
||||
val usernames = listOfNotNull(me.username) + me.activeUsernames
|
||||
onContentMessage(
|
||||
initialFilter = initialFilter@{ it.text ?.contains(me.username ?.full ?: return@initialFilter false) == true }
|
||||
initialFilter = { message ->
|
||||
usernames.any { message.text?.contains(it.full, ignoreCase = true) == true }
|
||||
}
|
||||
) { message ->
|
||||
val answerText = when (val chat = message.chat) {
|
||||
is PreviewChannelChat -> {
|
||||
|
||||
@@ -17,11 +17,9 @@ The bot also prints its own account information at startup, logs received update
|
||||
|
||||
## Setup
|
||||
|
||||
Create a bot and obtain its token, then enable inline mode for it in BotFather (for example, with `/setinline`). Keep the
|
||||
token private.
|
||||
|
||||
Both launchers require the bot token as the first command-line argument. Starting either launcher without an argument
|
||||
fails immediately; additional arguments are ignored.
|
||||
Create a bot and obtain its token. To enable inline mode and set the search placeholder through `setMySettings`,
|
||||
pass `configureInline` after the token on either launcher. Telegram saves both settings, so subsequent launches only
|
||||
need the token. You can also enable inline mode through BotFather.
|
||||
|
||||
## Launch from the repository root
|
||||
|
||||
@@ -31,6 +29,12 @@ fails immediately; additional arguments are ignored.
|
||||
./gradlew :InlineQueriesBot:runJvm --args="<BOT_TOKEN>"
|
||||
```
|
||||
|
||||
To configure inline mode on the first run:
|
||||
|
||||
```bash
|
||||
./gradlew :InlineQueriesBot:runJvm --args="<BOT_TOKEN> configureInline"
|
||||
```
|
||||
|
||||
### Kotlin/Native
|
||||
|
||||
The shared native configuration supports Linux x64/Arm64 and Windows x64 hosts. Build the debug executable with Gradle,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import dev.inmo.micro_utils.coroutines.subscribeLoggingDropExceptions
|
||||
import dev.inmo.tgbotapi.extensions.api.answers.answer
|
||||
import dev.inmo.tgbotapi.extensions.api.bot.getMe
|
||||
import dev.inmo.tgbotapi.extensions.api.bot.setMySettings
|
||||
import dev.inmo.tgbotapi.extensions.api.send.reply
|
||||
import dev.inmo.tgbotapi.extensions.api.telegramBot
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.buildBehaviourWithLongPolling
|
||||
@@ -16,8 +17,14 @@ import dev.inmo.tgbotapi.utils.buildEntities
|
||||
/**
|
||||
* Starts the inline-query bot with [token] and suspends until long polling stops.
|
||||
*/
|
||||
suspend fun doInlineQueriesBot(token: String) {
|
||||
suspend fun doInlineQueriesBot(token: String, configureInline: Boolean = false) {
|
||||
val bot = telegramBot(token)
|
||||
if (configureInline) {
|
||||
bot.setMySettings(
|
||||
supportsInlineQueries = true,
|
||||
inlineQueryPlaceholder = "Search numbered articles"
|
||||
)
|
||||
}
|
||||
|
||||
bot.buildBehaviourWithLongPolling(
|
||||
defaultExceptionsHandler = { it.printStackTrace() },
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** JVM entry point; [args] must contain the bot token as its first element. */
|
||||
suspend fun main(args: Array<String>) {
|
||||
doInlineQueriesBot(args.first())
|
||||
doInlineQueriesBot(args.first(), configureInline = "configureInline" in args)
|
||||
}
|
||||
@@ -3,6 +3,6 @@ import kotlinx.coroutines.runBlocking
|
||||
/** Kotlin/Native entry point; [args] must contain the bot token as its first element. */
|
||||
fun main(args: Array<String>) {
|
||||
runBlocking {
|
||||
doInlineQueriesBot(args.first())
|
||||
doInlineQueriesBot(args.first(), configureInline = "configureInline" in args)
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="JoinRequestQueriesBotKt"
|
||||
application.mainClass = "JoinRequestQueriesBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -15,7 +15,7 @@ plugins {
|
||||
|
||||
kotlin {
|
||||
jvm()
|
||||
js(IR) {
|
||||
js {
|
||||
browser()
|
||||
binaries.executable()
|
||||
}
|
||||
|
||||
@@ -57,7 +57,11 @@ fun InlineKeyboardBuilder.includePageButtons(page: Int, count: Int) {
|
||||
val numbersRange = 1 .. count
|
||||
numericButtons.forEach {
|
||||
if (it in numbersRange) {
|
||||
dataButton(it.toString(), "$it $count")
|
||||
if (it == page) {
|
||||
disabledButton(it.toString(), style = KeyboardButtonStyle.Primary)
|
||||
} else {
|
||||
dataButton(it.toString(), "$it $count")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -101,7 +105,6 @@ fun InlineKeyboardBuilder.includePageButtons(page: Int, count: Int) {
|
||||
* @param token the Telegram bot token
|
||||
* @param print receives the bot information returned by the startup `getMe` request
|
||||
*/
|
||||
@OptIn(PreviewFeature::class)
|
||||
suspend fun activateKeyboardsBot(
|
||||
token: String,
|
||||
print: (Any) -> Unit
|
||||
@@ -117,7 +120,7 @@ suspend fun activateKeyboardsBot(
|
||||
val page = numberArgs.firstOrNull()?.takeIf { numberArgs.size > 1 }?.coerceAtLeast(1) ?: 1
|
||||
reply(
|
||||
message,
|
||||
replyMarkup = inlineKeyboard {
|
||||
replyMarkup = inlineKeyboard(forceReply = true) {
|
||||
includePageButtons(page, numberOfPages)
|
||||
}
|
||||
) {
|
||||
@@ -136,7 +139,7 @@ suspend fun activateKeyboardsBot(
|
||||
answer(it, "Unsupported message type :(")
|
||||
return@onMessageDataCallbackQuery
|
||||
},
|
||||
replyMarkup = inlineKeyboard {
|
||||
replyMarkup = inlineKeyboard(forceReply = true) {
|
||||
includePageButtons(page, count)
|
||||
}
|
||||
) {
|
||||
@@ -152,7 +155,7 @@ suspend fun activateKeyboardsBot(
|
||||
|
||||
editMessageText(
|
||||
it.inlineMessageId,
|
||||
replyMarkup = inlineKeyboard {
|
||||
replyMarkup = inlineKeyboard(forceReply = true) {
|
||||
includePageButtons(page, count)
|
||||
}
|
||||
) {
|
||||
@@ -173,7 +176,7 @@ suspend fun activateKeyboardsBot(
|
||||
InlineQueryId(it.query),
|
||||
"Send buttons",
|
||||
InputTextMessageContent("It is sent via inline mode inline buttons"),
|
||||
replyMarkup = inlineKeyboard {
|
||||
replyMarkup = inlineKeyboard(forceReply = true) {
|
||||
includePageButtons(page, count)
|
||||
}
|
||||
)
|
||||
@@ -184,7 +187,11 @@ suspend fun activateKeyboardsBot(
|
||||
onUnhandledCommand {
|
||||
reply(
|
||||
it,
|
||||
replyMarkup = replyKeyboard(resizeKeyboard = true, oneTimeKeyboard = true) {
|
||||
replyMarkup = replyKeyboard(
|
||||
resizeKeyboard = true,
|
||||
oneTimeKeyboard = true,
|
||||
forceReply = true,
|
||||
) {
|
||||
row {
|
||||
simpleButton("/inline", style = KeyboardButtonStyle.Primary)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# KeyboardsBot
|
||||
|
||||
A multiplatform long-polling example that demonstrates Telegram reply keyboards, inline keyboards, callback queries, copy-text buttons, inline-mode buttons, and keyboard button styles. The shared bot behavior lives in `KeyboardsBotLib`; the project provides a browser/JS entry point and a separate JVM launcher.
|
||||
A multiplatform long-polling example that demonstrates Telegram reply keyboards, inline keyboards, callback queries, copy-text buttons, inline-mode buttons, keyboard button styles, disabled buttons, and forced reply interfaces. The shared bot behavior lives in `KeyboardsBotLib`; the project provides a browser/JS entry point and a separate JVM launcher.
|
||||
|
||||
## Bot behavior
|
||||
|
||||
@@ -16,16 +16,16 @@ At startup, the bot calls `getMe`, reports the returned bot information through
|
||||
|
||||
Only numeric command arguments are considered. Use positive integers with `page <= count`; the example does not validate the count or clamp the page to the upper bound.
|
||||
|
||||
The generated inline keyboard contains:
|
||||
The generated inline keyboard sets Bot API 10.3's `force_reply` field and contains:
|
||||
|
||||
- numbered buttons for the current page and any adjacent pages that are within `1..count`;
|
||||
- a disabled button for the current page and callback buttons for adjacent pages within `1..count`;
|
||||
- styled jump buttons for moving toward the first or last page when applicable;
|
||||
- a **Command copy button** that copies `/inline <page> <count>`;
|
||||
- a **Send somebody page** button that starts inline mode and lets the user choose a user, bot, group, or channel.
|
||||
|
||||
Pagination callbacks edit the original message and replace its text with `This is <page> of <count>`. This works for both ordinary bot messages and messages sent through inline mode. Unsupported callback data or an unsupported message type is answered with a callback notification instead.
|
||||
|
||||
Any command not handled above, including `/start`, receives a one-time reply keyboard containing a styled `/inline` button. Ordinary non-command messages are ignored.
|
||||
Any command not handled above, including `/start`, receives a one-time reply keyboard containing a styled `/inline` button. That reply keyboard also sets `force_reply`, demonstrating the field on both markup types. Ordinary non-command messages are ignored.
|
||||
|
||||
### Inline mode
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="KeyboardsBotJvmKt"
|
||||
application.mainClass = "KeyboardsBotJvmKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="LinkPreviewsBotKt"
|
||||
application.mainClass = "LinkPreviewsBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="LiveLocationsBotKt"
|
||||
application.mainClass = "LiveLocationsBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
+10
-4
@@ -8,17 +8,23 @@ The bot defines no commands. It prints every incoming update to standard output
|
||||
|
||||
| Trigger | Behavior |
|
||||
| --- | --- |
|
||||
| Standalone Live Photo | Logs its file identifiers, dimensions, duration, thumbnail, MIME type, size, and caption. It resends the Live Photo, sends the same media as paid content costing 1 Star, and then edits the resent message with `TelegramMediaLivePhoto`. |
|
||||
| Live Photo gallery | Logs every item and resends the gallery with `sendMediaGroup`. |
|
||||
| Standalone Live Photo | Logs its file identifiers, dimensions, duration, thumbnail, MIME type, size, and caption. It resends the Live Photo by file ID, downloads both components, edits the resent message with new multipart files, and uploads the files again as paid content costing 1 Star. |
|
||||
| Live Photo gallery | Logs every item, downloads each main and cover file, and re-uploads the gallery with `sendMediaGroup`. |
|
||||
| Paid-media message containing Live Photos | Logs each Live Photo and replies with the number found. Paid-media messages without a Live Photo get no reply from this handler. |
|
||||
| Edited Live Photo | Logs the file ID and updated caption. |
|
||||
| Media group containing at least one regular photo and one regular video | Uses the first photo as the cover and the first video as the motion part, then replies with a Live Photo. Albums missing either type are ignored by this handler. |
|
||||
|
||||
## Live Photo handling
|
||||
|
||||
The bot does not download or transform media. It reuses Telegram file IDs: the received Live Photo is passed directly to `sendLivePhoto`, while its main file ID and thumbnail file ID are used to construct `TelegramMediaLivePhoto` and `TelegramPaidMediaLivePhoto`. If Telegram supplies no thumbnail, the code falls back to the main file ID for the photo field.
|
||||
The initial `sendLivePhoto` call reuses Telegram file IDs. The regular-media edit,
|
||||
paid-media send, and gallery resend then demonstrate ktgbotapi 37.0.0 collecting
|
||||
the secondary Live Photo `photo` attachment as well as the main multipart file.
|
||||
If Telegram supplies no cover photo, the code falls back to the main file ID for
|
||||
the `photo` field. Downloaded files are held in memory and are not transformed.
|
||||
|
||||
The standalone handler performs its requests in order: resend, send paid media, then edit the resent message. Consequently, a failure while sending paid media prevents the edit for that update.
|
||||
The standalone handler performs its requests in order: resend, download, edit,
|
||||
then send paid media. The edit can therefore succeed in a private or group chat
|
||||
before the channel-only paid-media request fails.
|
||||
|
||||
## Telegram setup and permissions
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="LivePhotosBotKt"
|
||||
application.mainClass = "LivePhotosBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -5,6 +5,7 @@ import dev.inmo.kslog.common.setDefaultKSLog
|
||||
import dev.inmo.micro_utils.coroutines.subscribeLoggingDropExceptions
|
||||
import dev.inmo.micro_utils.coroutines.subscribeSafelyWithoutExceptions
|
||||
import dev.inmo.tgbotapi.extensions.api.edit.media.editMessageMedia
|
||||
import dev.inmo.tgbotapi.extensions.api.files.downloadFile
|
||||
import dev.inmo.tgbotapi.extensions.api.send.media.sendLivePhoto
|
||||
import dev.inmo.tgbotapi.extensions.api.send.media.sendMediaGroup
|
||||
import dev.inmo.tgbotapi.extensions.api.send.media.sendPaidMedia
|
||||
@@ -23,6 +24,7 @@ import dev.inmo.tgbotapi.extensions.utils.photoFileOrNull
|
||||
import dev.inmo.tgbotapi.extensions.utils.videoContentOrNull
|
||||
import dev.inmo.tgbotapi.extensions.utils.videoFileOrNull
|
||||
import dev.inmo.tgbotapi.extensions.utils.withContentOrNull
|
||||
import dev.inmo.tgbotapi.requests.abstracts.asMultipartFile
|
||||
import dev.inmo.tgbotapi.types.message.content.LivePhotoContent
|
||||
import dev.inmo.tgbotapi.types.message.payments.PaidMedia
|
||||
import dev.inmo.tgbotapi.types.media.TelegramMediaLivePhoto
|
||||
@@ -90,34 +92,42 @@ suspend fun main(vararg args: String) {
|
||||
)
|
||||
println(" sent message id: ${sent.messageId}")
|
||||
|
||||
// InputPaidMediaLivePhoto (TelegramPaidMediaLivePhoto): send the live photo as paid media (1 star)
|
||||
sendPaidMedia(
|
||||
chatId = message.chat.id,
|
||||
starCount = 1,
|
||||
media = listOf(
|
||||
// TelegramPaidMediaLivePhoto is InputPaidMediaLivePhoto
|
||||
TelegramPaidMediaLivePhoto(
|
||||
file = livePhotoFile.fileId,
|
||||
photo = livePhotoFile.photo?.fileId ?: livePhotoFile.fileId
|
||||
)
|
||||
),
|
||||
text = "Paid live photo (1 star)"
|
||||
)
|
||||
// Download both Live Photo components once. ktgbotapi 37.0.0 collects the secondary `photo`
|
||||
// MultipartFile alongside the main file for edits, media groups, and paid-media requests.
|
||||
val livePhotoBytes = downloadFile(livePhotoFile)
|
||||
val coverPhotoBytes = livePhotoFile.photo?.let { downloadFile(it) }
|
||||
|
||||
// editMessageMedia with InputMediaLivePhoto (TelegramMediaLivePhoto):
|
||||
// edit the previously sent message to replace it with itself via TelegramMediaLivePhoto
|
||||
// edit the previously sent message using newly uploaded main and cover files.
|
||||
val sentAsMedia = sent.withContentOrNull<LivePhotoContent>()
|
||||
if (sentAsMedia != null) {
|
||||
editMessageMedia(
|
||||
message = sentAsMedia,
|
||||
// TelegramMediaLivePhoto is InputMediaLivePhoto
|
||||
media = TelegramMediaLivePhoto(
|
||||
file = livePhotoFile.fileId,
|
||||
photo = livePhotoFile.photo?.fileId ?: livePhotoFile.fileId,
|
||||
text = "Edited via editMessageMedia with TelegramMediaLivePhoto"
|
||||
file = livePhotoBytes.asMultipartFile("edited-live-photo.mp4"),
|
||||
photo = coverPhotoBytes?.asMultipartFile("edited-live-photo-cover.jpg")
|
||||
?: livePhotoFile.photo?.fileId
|
||||
?: livePhotoFile.fileId,
|
||||
text = "Edited with newly uploaded Live Photo files"
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
// InputPaidMediaLivePhoto (TelegramPaidMediaLivePhoto): upload both files as paid media (1 star).
|
||||
// Telegram currently restricts sendPaidMedia to channel chats.
|
||||
sendPaidMedia(
|
||||
chatId = message.chat.id,
|
||||
starCount = 1,
|
||||
media = listOf(
|
||||
TelegramPaidMediaLivePhoto(
|
||||
file = livePhotoBytes.asMultipartFile("paid-live-photo.mp4"),
|
||||
photo = coverPhotoBytes?.asMultipartFile("paid-live-photo-cover.jpg")
|
||||
?: livePhotoFile.photo?.fileId
|
||||
?: livePhotoFile.fileId
|
||||
)
|
||||
),
|
||||
text = "Paid live photo uploaded as new files (1 star)"
|
||||
)
|
||||
}
|
||||
|
||||
// Demonstrates: sendMediaGroup with live photos, InputMediaLivePhoto (TelegramMediaLivePhoto)
|
||||
@@ -128,15 +138,17 @@ suspend fun main(vararg args: String) {
|
||||
println(" - fileId: ${livePhotoFile.fileId}, ${livePhotoFile.width}x${livePhotoFile.height}")
|
||||
}
|
||||
|
||||
// sendMediaGroup with TelegramMediaLivePhoto (InputMediaLivePhoto)
|
||||
// sendMediaGroup with newly uploaded main and cover files for every TelegramMediaLivePhoto.
|
||||
sendMediaGroup(
|
||||
chatId = mediaGroupContent.group.first().sourceMessage.chat.id,
|
||||
media = mediaGroupContent.group.map { groupMember ->
|
||||
media = mediaGroupContent.group.mapIndexed { index, groupMember ->
|
||||
val livePhotoFile = groupMember.content.media
|
||||
// TelegramMediaLivePhoto is InputMediaLivePhoto — used here in sendMediaGroup
|
||||
val coverPhoto = livePhotoFile.photo
|
||||
TelegramMediaLivePhoto(
|
||||
file = livePhotoFile.fileId,
|
||||
photo = livePhotoFile.photo?.fileId ?: livePhotoFile.fileId
|
||||
file = downloadFile(livePhotoFile).asMultipartFile("gallery-live-photo-$index.mp4"),
|
||||
photo = coverPhoto?.let {
|
||||
downloadFile(it).asMultipartFile("gallery-live-photo-cover-$index.jpg")
|
||||
} ?: livePhotoFile.fileId
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
@@ -39,7 +39,7 @@ No chat-administrator permission is requested by the code.
|
||||
|
||||
## Run
|
||||
|
||||
The intended command from the repository root is:
|
||||
Run from the repository root:
|
||||
|
||||
```bash
|
||||
./gradlew :ManagedBotsBot:run --args="BOT_TOKEN"
|
||||
@@ -47,7 +47,3 @@ The intended command from the repository root is:
|
||||
|
||||
The first argument is the required token. Optional exact flags may follow it in any
|
||||
order: `debug` enables formatted logging, and `testServer` uses Telegram's test API.
|
||||
|
||||
Known issue: `build.gradle` currently sets `mainClassName` to `CustomBotKt`, while
|
||||
this source's entry point is `ManagedBotsBotKt`; the `run` task cannot start until
|
||||
that Gradle setting is corrected.
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="CustomBotKt"
|
||||
application.mainClass = "ManagedBotsBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="MemberUpdatedWatcherKt"
|
||||
application.mainClass = "MemberUpdatedWatcherKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
+4
-5
@@ -4,7 +4,8 @@ A long-polling example that prints information about the bot and lets Telegram u
|
||||
|
||||
## Behavior
|
||||
|
||||
At startup, the application prints the results of `getMe` and `getChat` for the bot itself to standard output. It then handles two commands:
|
||||
At startup, the application prints the `BotFullInfo` returned by `getMe`, including active usernames and bot settings.
|
||||
It passes that object's `id` to `getChat` to print the bot's chat profile. It then handles two commands:
|
||||
|
||||
- `/setMyProfilePhoto` replies with `ok, send me new photo` and waits for the first photo sent in the same chat. It streams draft progress messages while downloading the photo to a temporary file, uploads it as a static bot profile photo, and replies when the change is complete. The photo may come from any user in that chat; it is not restricted to the user who sent the command.
|
||||
- `/removeMyProfilePhoto` removes the bot's current profile photo and confirms success. On failure, it prints the exception and sends a generic error reply.
|
||||
@@ -24,13 +25,13 @@ There is no `/start` handler, and ordinary messages are ignored unless the bot i
|
||||
The first argument is always the required bot token. Optional arguments can follow it in any order:
|
||||
|
||||
- `debug` enables formatted default KSLog output.
|
||||
- `testServer` makes the behavior and long-polling client use Telegram's Bot API test environment. The initial `getMe` and `getChat` diagnostics currently use a separate default-server client.
|
||||
- `testServer` runs the startup diagnostics and polling against Telegram's Bot API test environment.
|
||||
|
||||
Other arguments are ignored. Argument matching is case-sensitive.
|
||||
|
||||
## Launch
|
||||
|
||||
The intended command from the repository root is:
|
||||
Run from the repository root:
|
||||
|
||||
```bash
|
||||
./gradlew :MyBot:run --args="<BOT_TOKEN>"
|
||||
@@ -41,5 +42,3 @@ For example, to enable both optional modes:
|
||||
```bash
|
||||
./gradlew :MyBot:run --args="<BOT_TOKEN> debug testServer"
|
||||
```
|
||||
|
||||
> **Known issue:** `MyBot/build.gradle` still declares the old `GetMeBotKt` main class, while the current source produces `MyBotKt`. Consequently, the `run` task cannot start until that build setting is corrected. It is left unchanged here because this example update is documentation-only.
|
||||
+1
-1
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="GetMeBotKt"
|
||||
application.mainClass = "MyBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -4,7 +4,6 @@ import dev.inmo.kslog.common.defaultMessageFormatter
|
||||
import dev.inmo.kslog.common.setDefaultKSLog
|
||||
import dev.inmo.micro_utils.coroutines.launchLoggingDropExceptions
|
||||
import dev.inmo.micro_utils.coroutines.runCatchingLogging
|
||||
import dev.inmo.tgbotapi.bot.ktor.telegramBot
|
||||
import dev.inmo.tgbotapi.extensions.api.bot.getMe
|
||||
import dev.inmo.tgbotapi.extensions.api.bot.removeMyProfilePhoto
|
||||
import dev.inmo.tgbotapi.extensions.api.bot.setMyProfilePhoto
|
||||
@@ -47,16 +46,14 @@ suspend fun main(vararg args: String) {
|
||||
)
|
||||
}
|
||||
|
||||
val bot = telegramBot(botToken)
|
||||
|
||||
telegramBotWithBehaviourAndLongPolling(
|
||||
botToken,
|
||||
CoroutineScope(Dispatchers.Default),
|
||||
testServer = isTestServer,
|
||||
) {
|
||||
val me = bot.getMe()
|
||||
val me = getMe()
|
||||
println(me)
|
||||
println(bot.getChat(me))
|
||||
println(getChat(me.id))
|
||||
|
||||
onCommand("setMyProfilePhoto") { commandMessage ->
|
||||
reply(commandMessage, "ok, send me new photo")
|
||||
|
||||
+1
-5
@@ -43,7 +43,7 @@ chat and client that support them.
|
||||
|
||||
## Run
|
||||
|
||||
The intended command from the repository root is:
|
||||
Run from the repository root:
|
||||
|
||||
```bash
|
||||
./gradlew :PollsBot:run --args="BOT_TOKEN"
|
||||
@@ -51,7 +51,3 @@ The intended command from the repository root is:
|
||||
|
||||
The first argument is the required token. An optional exact `debug` argument in any
|
||||
later position enables formatted logging; other arguments are ignored.
|
||||
|
||||
Known issue: `build.gradle` currently names `HelloBotKt` as the main class, while
|
||||
this source's entry point is `PollsBotKt`; the `run` task cannot start until that
|
||||
Gradle setting is corrected.
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="HelloBotKt"
|
||||
application.mainClass = "PollsBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
# TelegramBotAPI examples
|
||||
|
||||
Runnable examples for [TelegramBotAPI](https://github.com/InsanusMokrassar/TelegramBotAPI). Each module focuses on a small Telegram Bot API feature and has its own README with detailed behavior, setup, permissions, and optional arguments.
|
||||
Runnable examples for [TelegramBotAPI](https://github.com/InsanusMokrassar/TelegramBotAPI) 38.0.0, covering Telegram Bot API 10.4 and 10.5. This branch uses `dev.inmo:tgbotapi:38.0.0-t1` from Maven Local. Each module has a README with its behavior, setup, permissions, and launch arguments.
|
||||
|
||||
## Running an example
|
||||
|
||||
If `38.0.0-t1` is missing from Maven Local, run `./gradlew -Plibrary_version=38.0.0-t1 publishToMavenLocal`
|
||||
in the TelegramBotAPI `38.0.0` checkout.
|
||||
|
||||
When updating an existing examples checkout, run `./gradlew kotlinUpgradeYarnLock` if Kotlin/JS reports
|
||||
that the local `yarn.lock` has changed.
|
||||
|
||||
Run commands from the repository root and replace placeholders such as `<BOT_TOKEN>` and `<ADMIN_USER_ID>`. The table uses JVM launchers for multiplatform modules; their module READMEs also document browser and native targets where available.
|
||||
|
||||
The shortcuts include all mode tokens supported by each launcher. Remove `debug` to disable verbose logging and remove `testServer` to use Telegram's production Bot API. These are positional values inside `--args` and intentionally have no leading dashes: the current launchers recognize `debug`, not `--debug`, and `testServer`, not `--testServer`.
|
||||
The shortcuts show `debug` and `testServer` where supported. Pass them as bare words inside `--args`. Omit `debug` for normal logging and `testServer` to use Telegram's production Bot API.
|
||||
|
||||
`InlineQueriesBot` accepts `configureInline` to enable inline mode. `EphemeralMessagesBot` accepts `inlineCallbacks` or `defaultCallbacks` to select how Telegram delivers button presses. Telegram saves these settings across runs. [Inline query setup](InlineQueriesBot/README.md#setup) · [Ephemeral callback modes](EphemeralMessagesBot/README.md#run)
|
||||
|
||||
Native targets on Linux require libcurl development files, for example:
|
||||
|
||||
@@ -20,40 +28,40 @@ sudo apt install libcurl4-gnutls-dev
|
||||
| --- | --- | --- |
|
||||
| [BoostsInfoBot](BoostsInfoBot/) | Requests a channel, lists the requesting user's boosts, and logs boost updates. | `./gradlew :BoostsInfoBot:run --args="<BOT_TOKEN> debug"` |
|
||||
| [BotSubscriptionsBot](BotSubscriptionsBot/) | Observes recurring Telegram Stars subscription state updates. | `./gradlew :BotSubscriptionsBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [BusinessConnectionsBot](BusinessConnectionsBot/) | Manages a connected Business account, messages, Stars, gifts, stories, and checklists. | `./gradlew :BusinessConnectionsBot:run --args="<BOT_TOKEN> debug"` |
|
||||
| [BusinessConnectionsBot](BusinessConnectionsBot/) | Manages a connected business account, including deletion of regular gifts by owned ID. | `./gradlew :BusinessConnectionsBot:run --args="<BOT_TOKEN> debug"` |
|
||||
| [ChatAvatarSetter](ChatAvatarSetter/) | Sets a chat photo from an image sent to the bot. | `./gradlew :ChatAvatarSetter:run --args="<BOT_TOKEN>"` |
|
||||
| [ChatManagementBot](ChatManagementBot/) | Exercises member permissions, administrator queries, reaction deletion, and bot-to-bot messages. | `./gradlew :ChatManagementBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [ChecklistsBot](ChecklistsBot/) | Receives and renders checklist messages and checklist service events. | `./gradlew :ChecklistsBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [CommunitiesBot](CommunitiesBot/) | Handles community join/leave events and inspects a chat's current community. | `./gradlew :CommunitiesBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [CommunitiesBot](CommunitiesBot/) | Handles chat/community membership and user-from-community join events. | `./gradlew :CommunitiesBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [CustomBot](CustomBot/) | Provides a diagnostics playground for contexts, request logging, profile audio, and Stars balance. | `./gradlew :CustomBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [DeepLinksBot](DeepLinksBot/) | Generates bot deep links and consumes their start payloads. | `./gradlew :DeepLinksBot:run --args="<BOT_TOKEN>"` |
|
||||
| [DraftsBot](DraftsBot/) † | Streams message drafts before sending the completed message. | `./gradlew :DraftsBot:run --args="<BOT_TOKEN>"` |
|
||||
| [EphemeralMessagesBot](EphemeralMessagesBot/) | Sends ephemeral messages revealed through an inline button. | `./gradlew :EphemeralMessagesBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [DeepLinksBot](DeepLinksBot/) | Generates deep links and owner invitations, handles start payloads, and inspects chat share themes. | `./gradlew :DeepLinksBot:run --args="<BOT_TOKEN>"` |
|
||||
| [DraftsBot](DraftsBot/) | Streams empty or stoppable message drafts and handles generation-stopped updates. | `./gradlew :DraftsBot:run --args="<BOT_TOKEN>"` |
|
||||
| [EphemeralMessagesBot](EphemeralMessagesBot/) | Sends ephemeral replies to callbacks and edits photos and Live Photos for a single recipient. | `./gradlew :EphemeralMessagesBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [FSMBot](FSMBot/) | Implements a conversational finite-state machine with chat-scoped in-memory state. | `./gradlew :FSMBot:run --args="<BOT_TOKEN>"` |
|
||||
| [FilesLoaderBot](FilesLoaderBot/) | Downloads incoming media to disk and sends it back to the chat. | `./gradlew :FilesLoaderBot:run --args="<BOT_TOKEN> <OUTPUT_DIRECTORY>"` |
|
||||
| [ForwardInfoSenderBot](ForwardInfoSenderBot/) | Reports the forward-origin metadata of received content. | `./gradlew :ForwardInfoSenderBot:run --args="<BOT_TOKEN>"` |
|
||||
| [GiftsBot](GiftsBot/) | Paginates and lists gifts owned by a user or chat. | `./gradlew :GiftsBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [GiftsBot](GiftsBot/) | Lists owned gifts, looks up unique gifts by name, and displays gift events. | `./gradlew :GiftsBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [GiveawaysBot](GiveawaysBot/) | Logs giveaway creation, completion, and winner events. | `./gradlew :GiveawaysBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [GuestQueryBot](GuestQueryBot/) | Handles guest queries in chats where the bot is not a member. | `./gradlew :GuestQueryBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [HelloBot](HelloBot/) | Greets users, groups, channels, or business chats when mentioned. | `./gradlew :HelloBot:run --args="<BOT_TOKEN>"` |
|
||||
| [InlineQueriesBot](InlineQueriesBot/) | Answers inline queries and supplies a deep-link result. | `./gradlew :InlineQueriesBot:runJvm --args="<BOT_TOKEN>"` |
|
||||
| [InlineQueriesBot](InlineQueriesBot/) | Configures inline mode, answers paginated queries, and supplies a deep-link result. | `./gradlew :InlineQueriesBot:runJvm --args="<BOT_TOKEN>"` |
|
||||
| [JoinRequestQueriesBot](JoinRequestQueriesBot/) | Queues or approves join requests, optionally delegating the decision to a Web App. | `./gradlew :JoinRequestQueriesBot:run --args="<BOT_TOKEN> https://example.com/verify debug testServer"` |
|
||||
| [KeyboardsBot](KeyboardsBot/) | Demonstrates reply, inline, callback, paged, copy-text, and inline-mode keyboards. | `./gradlew :KeyboardsBot:jvm_launcher:run --args="<BOT_TOKEN> debug"` |
|
||||
| [KeyboardsBot](KeyboardsBot/) | Demonstrates reply, inline, disabled, forced-reply, paged, and inline-mode keyboards. | `./gradlew :KeyboardsBot:jvm_launcher:run --args="<BOT_TOKEN> debug"` |
|
||||
| [LinkPreviewsBot](LinkPreviewsBot/) | Sends the same link using multiple link-preview configurations. | `./gradlew :LinkPreviewsBot:run --args="<BOT_TOKEN> debug"` |
|
||||
| [LiveLocationsBot](LiveLocationsBot/) | Sends, updates, cancels, and stops a live-location message. | `./gradlew :LiveLocationsBot:run --args="<BOT_TOKEN>"` |
|
||||
| [LivePhotosBot](LivePhotosBot/) | Receives, sends, groups, edits, and sells Telegram Live Photos. | `./gradlew :LivePhotosBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [ManagedBotsBot](ManagedBotsBot/) † | Creates and administers managed bots and inspects personal-channel messages. | `./gradlew :ManagedBotsBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [LivePhotosBot](LivePhotosBot/) | Receives, uploads, groups, edits, and sells Telegram Live Photos. | `./gradlew :LivePhotosBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [ManagedBotsBot](ManagedBotsBot/) | Creates and administers managed bots and inspects personal-channel messages. | `./gradlew :ManagedBotsBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [MemberUpdatedWatcherBot](MemberUpdatedWatcherBot/) | Logs and reports bot/member status transitions in chats. | `./gradlew :MemberUpdatedWatcherBot:run --args="<BOT_TOKEN> debug"` |
|
||||
| [MyBot](MyBot/) † | Replaces or removes the bot's global profile photo and prints diagnostics. | `./gradlew :MyBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [PollsBot](PollsBot/) † | Sends regular polls, quizzes, poll media, and handles poll updates. | `./gradlew :PollsBot:run --args="<BOT_TOKEN> debug"` |
|
||||
| [MyBot](MyBot/) | Replaces or removes the bot's global profile photo and prints diagnostics. | `./gradlew :MyBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [PollsBot](PollsBot/) | Sends regular polls, quizzes, poll media, and handles poll updates. | `./gradlew :PollsBot:run --args="<BOT_TOKEN> debug"` |
|
||||
| [RandomFileSenderBot](RandomFileSenderBot/) | Picks random local files and sends them individually or as media groups. | `./gradlew :RandomFileSenderBot:runJvm --args="<BOT_TOKEN> <FILES_DIRECTORY>"` |
|
||||
| [ReactionsInfoBot](ReactionsInfoBot/) | Handles per-user reaction changes and anonymous reaction-count updates. | `./gradlew :ReactionsInfoBot:run --args="<BOT_TOKEN> debug"` |
|
||||
| [ResenderBot](ResenderBot/) | Recreates received content while preserving reply, quote, effect, and business context. | `./gradlew :ResenderBot:jvm_launcher:run --args="<BOT_TOKEN> debug"` |
|
||||
| [RichMessagesBot](RichMessagesBot/) | Demonstrates rich HTML/Markdown/blocks, streaming drafts, inline results, and media. | `./gradlew :RichMessagesBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [RightsChangerBot](RightsChangerBot/) | Uses an FSM and inline keyboards to change member and administrator rights. | `./gradlew :RightsChangerBot:run --args="<BOT_TOKEN> <ALLOWED_USER_ID> debug"` |
|
||||
| [RichMessagesBot](RichMessagesBot/) | Builds expandable quotations with paragraphs and lists, and replies to rich-text selections. | `./gradlew :RichMessagesBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [RightsChangerBot](RightsChangerBot/) | Changes member and administrator rights, and demonstrates linked third-party verification descriptions. | `./gradlew :RightsChangerBot:run --args="<BOT_TOKEN> <ALLOWED_USER_ID> debug"` |
|
||||
| [SlotMachineDetectorBot](SlotMachineDetectorBot/) | Detects slot-machine dice and decodes their reel values. | `./gradlew :SlotMachineDetectorBot:run --args="<BOT_TOKEN>"` |
|
||||
| [StarTransactionsBot](StarTransactionsBot/) | Demonstrates Stars invoices, transaction history, paid media, and refunds. | `./gradlew :StarTransactionsBot:run --args="<BOT_TOKEN> <ADMIN_USER_ID> debug testServer"` |
|
||||
| [StickerInfoBot](StickerInfoBot/) † | Looks up sticker-set metadata for stickers and custom emoji. | `./gradlew :StickerInfoBot:jvm_launcher:run --args="<BOT_TOKEN>"` |
|
||||
| [StarTransactionsBot](StarTransactionsBot/) | Handles Stars payments, paid-message waivers, TON wallet cards, and transfer events. | `./gradlew :StarTransactionsBot:run --args="<BOT_TOKEN> <ADMIN_USER_ID> debug testServer"` |
|
||||
| [StickerInfoBot](StickerInfoBot/) | Looks up sticker-set metadata for stickers and custom emoji. | `./gradlew :StickerInfoBot:jvm_launcher:run --args="<BOT_TOKEN>"` |
|
||||
| [StickerSetHandler](StickerSetHandler/) | Creates and manages a sticker set owned by each private-chat user. | `./gradlew :StickerSetHandler:run --args="<BOT_TOKEN>"` |
|
||||
| [SuggestedPosts](SuggestedPosts/) | Handles channel direct messages and the suggested-post lifecycle. | `./gradlew :SuggestedPosts:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
| [TagsBot](TagsBot/) | Sets chat-member tags, delegates tag management, and reads sender tags. | `./gradlew :TagsBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
@@ -61,8 +69,7 @@ sudo apt install libcurl4-gnutls-dev
|
||||
| [UserChatShared](UserChatShared/) | Requests users or chats through reply keyboards and handles the shared results. | `./gradlew :UserChatShared:run --args="<BOT_TOKEN> debug"` |
|
||||
| [WebApp](WebApp/) | Serves a Compose Web client and demonstrates Telegram Web App integration. | `./gradlew :WebApp:runJvm --args="<BOT_TOKEN> https://webapp.example 8080 debug testServer"` |
|
||||
| [WebHooks](WebHooks/) | Receives Telegram updates through a Ktor webhook server instead of long polling. | `./gradlew :WebHooks:run --args="<BOT_TOKEN> https://bot.example.com debug"` |
|
||||
|
||||
† These modules currently contain a stale Gradle `mainClassName` mapping, documented in their module README. The shown command is the intended launch command but will not start until that mapping is corrected.
|
||||
| [WidgetsBot](WidgetsBot/) | Sends interactive HTML dice directly or inline, answers widget queries, and updates individual or shared rolls. | `./gradlew :WidgetsBot:run --args="<BOT_TOKEN> debug testServer"` |
|
||||
|
||||
## Repository as a reference
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="ReactionsInfoBotKt"
|
||||
application.mainClass = "ReactionsInfoBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -8,8 +8,8 @@ points start it in platform-specific ways.
|
||||
|
||||
The bot defines no commands. For each content message, it shows a typing action and
|
||||
uses `createResend` to send equivalent content back to the originating chat. When
|
||||
present, it carries over the replied-to message metadata, text quote entities and
|
||||
position, and the message effect ID.
|
||||
present, it carries over the replied-to message metadata, quote entities, rich-text
|
||||
selections, their UTF-16 position, and the message effect ID.
|
||||
|
||||
Business content sent by the business-connection owner is ignored; other delivered
|
||||
content messages are eligible. Processing is separated by chat. The bot prints each
|
||||
|
||||
@@ -15,8 +15,7 @@ plugins {
|
||||
|
||||
kotlin {
|
||||
jvm()
|
||||
// js(LEGACY) {
|
||||
js(IR) {
|
||||
js {
|
||||
browser()
|
||||
binaries.executable()
|
||||
}
|
||||
|
||||
@@ -9,10 +9,9 @@ import dev.inmo.tgbotapi.extensions.behaviour_builder.telegramBotWithBehaviourAn
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onContentMessage
|
||||
import dev.inmo.tgbotapi.extensions.utils.possiblyWithEffectMessageOrNull
|
||||
import dev.inmo.tgbotapi.extensions.utils.shortcuts.executeUnsafe
|
||||
import dev.inmo.tgbotapi.extensions.utils.withContentOrNull
|
||||
import dev.inmo.tgbotapi.types.ReplyParameters
|
||||
import dev.inmo.tgbotapi.types.abstracts.WithOptionalQuoteInfo
|
||||
import dev.inmo.tgbotapi.types.message.abstracts.BusinessContentMessage
|
||||
import dev.inmo.tgbotapi.types.message.content.TextContent
|
||||
import dev.inmo.tgbotapi.utils.DefaultKTgBotAPIKSLog
|
||||
import dev.inmo.tgbotapi.utils.extensions.threadIdOrNull
|
||||
import kotlinx.coroutines.CancellationException
|
||||
@@ -49,11 +48,13 @@ suspend fun activateResenderBot(
|
||||
it.content.createResend(
|
||||
chat.id,
|
||||
replyParameters = it.replyInfo?.messageMeta?.let { meta ->
|
||||
val quote = it.withContentOrNull<TextContent>()?.content?.quote
|
||||
val quote = (it.content as? WithOptionalQuoteInfo)?.quote
|
||||
?: return@let ReplyParameters(meta)
|
||||
ReplyParameters(
|
||||
meta,
|
||||
entities = quote?.textSources ?: emptyList(),
|
||||
quotePosition = quote?.position
|
||||
entities = quote.textSources,
|
||||
quotePosition = quote.position,
|
||||
quoteRichTexts = quote.richTexts
|
||||
)
|
||||
},
|
||||
effectId = it.possiblyWithEffectMessageOrNull()?.effectId
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="ResenderBotJvmKt"
|
||||
application.mainClass = "ResenderBotJvmKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
+25
-14
@@ -1,13 +1,14 @@
|
||||
# RichMessagesBot
|
||||
|
||||
RichMessagesBot is a long-polling showcase of Telegram rich messages. It sends
|
||||
rich content from HTML, Markdown, and the typed `InputRichMessageBlocks` DSL;
|
||||
streams drafts; edits rich text; handles incoming rich messages; and supplies
|
||||
rich content from inline and guest queries.
|
||||
HTML, Markdown, and typed `InputRichMessageBlocks`, streams drafts, edits rich
|
||||
text, and answers inline and guest queries. Its examples include buttons, compact
|
||||
tables, document uploads, expandable quotations with nested blocks, TON addresses,
|
||||
and replies that preserve a user's rich-text selection.
|
||||
|
||||
## Commands
|
||||
|
||||
The bot installs seven commands in Telegram's default command menu. Three
|
||||
The bot installs nine commands in Telegram's default command menu. Three
|
||||
additional handlers can be invoked by typing their commands manually.
|
||||
|
||||
| Command | In menu | Demonstration |
|
||||
@@ -18,21 +19,31 @@ additional handlers can be invoked by typing their commands manually.
|
||||
| `/rich_markdown_blocks` | No | Sends and logs the full fixture as a typed block tree, including first-class media blocks, captions, collages, and slideshows. |
|
||||
| `/rich_markdown_medialess_blocks` | No | Sends and logs the same typed block tree without its media section. |
|
||||
| `/rich_blocks` | Yes | Sends a smaller, directly constructed block tree with headings, formatted paragraphs, ordered and unordered checkbox lists, a divider, preformatted Kotlin, and a quotation. |
|
||||
| `/rich_draft` | Yes | Streams three Markdown revisions under draft ID `1`, one second apart, then sends a normal final rich message. |
|
||||
| `/rich_blocks_draft` | Yes | Streams two draft-only `thinking()` blocks under draft ID `2`, one second apart, then sends a normal typed-block answer. |
|
||||
| `/rich_10_3` | Yes | Sends an inline `RichTextButton`, three aligned `InputRichBlockButtons` rows with URL, callback, inline-query, copy-text, and disabled actions, a compact table, an expandable quotation, and a document block. |
|
||||
| `/rich_quote` | Yes | Sends an expandable quotation containing a formatted paragraph and a list with a typed TON address. Send the command as a quoted reply to reproduce the selected passage. |
|
||||
| `/rich_draft` | Yes | In a private chat, streams three Markdown revisions with `canStop` and `keepOnStop`, one second apart, then sends a normal final rich message unless generation is stopped. |
|
||||
| `/rich_blocks_draft` | Yes | In a private chat, streams two draft-only `thinking()` blocks with `canStop` and `keepOnStop`, then sends a normal typed-block answer unless generation is stopped. |
|
||||
| `/rich_edit` | Yes | Sends a Markdown rich message, waits two seconds, and replaces its rich content with `EditChatMessageRichText`. |
|
||||
| `/wait_rich` | Yes | Prompts for a rich message, waits for the next matching content, and reports its block count. |
|
||||
|
||||
The two draft examples finalize by sending a new normal rich message; they do not
|
||||
turn the draft itself into the final message. They use distinct fixed IDs (`1`
|
||||
and `2`); concurrent runs of the same command in one chat reuse that command's
|
||||
ID.
|
||||
To try a rich-text selection, send `/rich_quote`, expand the address book, select
|
||||
some text, and reply to that selection with `/rich_quote`. The bot replies to the
|
||||
original address book using the received `TextQuote.richTexts` as `quoteRichTexts`
|
||||
and the received UTF-16 offset as `quotePosition`. Telegram counts UTF-16 code
|
||||
units across quotable texts separated by line feeds.
|
||||
|
||||
The two draft examples allocate a unique draft ID and subscribe to
|
||||
`waitMessageGenerationStopped` before sending the first revision. They finalize
|
||||
by sending a new normal rich message only if no matching stop update arrives;
|
||||
when stopped, they leave the retained draft untouched and log the event.
|
||||
|
||||
## Other triggers
|
||||
|
||||
| Trigger | Behavior |
|
||||
| --- | --- |
|
||||
| Any photo | Reuses the received Telegram file ID without downloading it. The bot first sends HTML whose `tg://photo?id=userphoto` reference is resolved by `InputRichMessageMedia`, then sends the same photo as a typed `photo()` block. |
|
||||
| Any document | Reuses the received file ID through a `tg://document?id=userdocument` HTML reference, then downloads the file and sends it again as a multipart upload nested in a typed `document()` block. Large documents are therefore held in memory. |
|
||||
| A `rich_10_3_callback` rich button | Answers the callback with a notification confirming that the rich-message button was received. |
|
||||
| Any incoming rich message | Logs right-to-left state and every parsed block, replies with the block count, and resends the rich message with `createResend`. The `onlyRichMessageContentMessages` flow also logs its block count. |
|
||||
| Any inline query | Returns uncached HTML and Markdown articles whose selected messages use `InputRichMessageContent`. |
|
||||
| A text guest request containing `/rich_guest` | Returns one inline article containing the full Markdown fixture. This is a substring check, not a registered bot command. Non-text guest requests and text without that exact case-sensitive substring are ignored by this handler. |
|
||||
@@ -50,9 +61,9 @@ Telegram file ID and assigning an alias for a `tg://photo?id=...` reference.
|
||||
|
||||
The source also shows the two library shapes used for rich media: an
|
||||
`InputRichMessageMedia` mapping for markup references and first-class photo,
|
||||
video, audio, voice-note, animation, collage, and slideshow blocks. The library
|
||||
can collect multipart files nested in a rich-message tree as `attach://` uploads,
|
||||
although this example's running handlers use URLs or an existing file ID.
|
||||
video, audio, voice-note, animation, document, collage, and slideshow blocks.
|
||||
The document trigger demonstrates the library collecting a multipart file nested
|
||||
in a rich-message tree as an `attach://` upload.
|
||||
|
||||
## Telegram setup and permissions
|
||||
|
||||
@@ -60,7 +71,7 @@ although this example's running handlers use URLs or an existing file ID.
|
||||
control.
|
||||
2. Start a private chat with the bot, or add it to a chat and allow it to send
|
||||
messages and media.
|
||||
3. To test ordinary photo and rich-message triggers in a group, ensure Telegram
|
||||
3. To test ordinary photo, document, and rich-message triggers in a group, ensure Telegram
|
||||
delivers non-command messages to the bot, for example by disabling Group
|
||||
Privacy Mode or making the bot an administrator.
|
||||
4. Enable Inline Mode in BotFather to exercise the inline-query results.
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="RichMessagesBotKt"
|
||||
application.mainClass = "RichMessagesBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -5,54 +5,79 @@ import dev.inmo.kslog.common.setDefaultKSLog
|
||||
import dev.inmo.micro_utils.coroutines.subscribeLoggingDropExceptions
|
||||
import dev.inmo.tgbotapi.extensions.api.answers.answer
|
||||
import dev.inmo.tgbotapi.extensions.api.bot.setMyCommands
|
||||
import dev.inmo.tgbotapi.extensions.api.files.downloadFile
|
||||
import dev.inmo.tgbotapi.extensions.api.send.reply
|
||||
import dev.inmo.tgbotapi.extensions.api.send.sendMessage
|
||||
import dev.inmo.tgbotapi.extensions.api.send.sendRichMessage
|
||||
import dev.inmo.tgbotapi.extensions.api.send.sendRichMessageDraft
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitMessageGenerationStopped
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitRichMessage
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.telegramBotWithBehaviourAndLongPolling
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onBaseInlineQuery
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommand
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onDataCallbackQuery
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onDocument
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onGuestRequestMessage
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onPhoto
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onRichMessage
|
||||
import dev.inmo.tgbotapi.extensions.utils.baseSentMessageUpdateOrNull
|
||||
import dev.inmo.tgbotapi.extensions.utils.contentMessageOrNull
|
||||
import dev.inmo.tgbotapi.extensions.utils.extensions.sameChat
|
||||
import dev.inmo.tgbotapi.extensions.utils.onlyRichMessageContentMessages
|
||||
import dev.inmo.tgbotapi.extensions.utils.withContentOrNull
|
||||
import dev.inmo.tgbotapi.requests.edit.text.EditChatMessageRichText
|
||||
import dev.inmo.tgbotapi.requests.abstracts.InputFile
|
||||
import dev.inmo.tgbotapi.requests.abstracts.asMultipartFile
|
||||
import dev.inmo.tgbotapi.types.BotCommand
|
||||
import dev.inmo.tgbotapi.types.CustomEmojiId
|
||||
import dev.inmo.tgbotapi.types.DateTimeEntityFormatting
|
||||
import dev.inmo.tgbotapi.types.InlineQueries.InlineQueryResult.InlineQueryResultArticle
|
||||
import dev.inmo.tgbotapi.types.InlineQueries.InputMessageContent.InputRichMessageContent
|
||||
import dev.inmo.tgbotapi.types.InlineQueryId
|
||||
import dev.inmo.tgbotapi.types.ReplyParameters
|
||||
import dev.inmo.tgbotapi.types.TelegramDate
|
||||
import dev.inmo.tgbotapi.types.chat.PrivateChat
|
||||
import dev.inmo.tgbotapi.types.message.content.TextContent
|
||||
import dev.inmo.tgbotapi.types.message.textsources.BotCommandTextSource
|
||||
import dev.inmo.tgbotapi.types.media.TelegramMediaAnimation
|
||||
import dev.inmo.tgbotapi.types.media.TelegramMediaAudio
|
||||
import dev.inmo.tgbotapi.types.media.TelegramMediaDocument
|
||||
import dev.inmo.tgbotapi.types.media.TelegramMediaPhoto
|
||||
import dev.inmo.tgbotapi.types.media.TelegramMediaVideo
|
||||
import dev.inmo.tgbotapi.types.media.TelegramMediaVoiceNote
|
||||
import dev.inmo.tgbotapi.types.payments.ton.TonAddress
|
||||
import dev.inmo.tgbotapi.types.rich.InputRichMessage
|
||||
import dev.inmo.tgbotapi.types.rich.InputRichMessageBlocks
|
||||
import dev.inmo.tgbotapi.types.rich.InputRichMessageHTML
|
||||
import dev.inmo.tgbotapi.types.rich.InputRichMessageMarkdown
|
||||
import dev.inmo.tgbotapi.types.rich.InputRichMessageMedia
|
||||
import dev.inmo.tgbotapi.types.rich.RichBlockCaption
|
||||
import dev.inmo.tgbotapi.types.rich.RichBlockButtonAlignment
|
||||
import dev.inmo.tgbotapi.types.rich.RichBlockTableCellAlign
|
||||
import dev.inmo.tgbotapi.types.rich.RichBlockTableCellVAlign
|
||||
import dev.inmo.tgbotapi.types.rich.RichMessageButton
|
||||
import dev.inmo.tgbotapi.types.rich.RichMessageButtonStyle
|
||||
import dev.inmo.tgbotapi.types.rich.RichTextPlain
|
||||
import dev.inmo.tgbotapi.types.rich.buildRichText
|
||||
import dev.inmo.tgbotapi.types.buttons.InlineKeyboardButtons.CopyTextButtonData
|
||||
import dev.inmo.tgbotapi.types.buttons.InlineKeyboardButtons.SwitchInlineQueryChosenChat
|
||||
import dev.inmo.tgbotapi.types.directMessageThreadIdOrMessageThreadIdAsDirectMessageThreadId
|
||||
import dev.inmo.tgbotapi.types.toChatId
|
||||
import dev.inmo.tgbotapi.utils.DraftIdAllocator
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.filter
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.mapNotNull
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
private val richDraftIds = DraftIdAllocator()
|
||||
|
||||
/**
|
||||
* Runs a long-polling showcase of the rich-message APIs introduced in Telegram Bot API 10.1 and 10.2.
|
||||
* Runs a long-polling showcase of Telegram's rich-message APIs.
|
||||
*
|
||||
* Outgoing [dev.inmo.tgbotapi.types.rich.InputRichMessage] values use one of three representations:
|
||||
* [InputRichMessageHTML], [InputRichMessageMarkdown], or a typed [InputRichMessageBlocks] tree of
|
||||
@@ -60,7 +85,10 @@ import kotlinx.coroutines.flow.mapNotNull
|
||||
* [sendRichMessageDraft] revisions sharing a draft ID (including draft-only `thinking()` blocks), and edits
|
||||
* through [EditChatMessageRichText]. Media is shown both as [InputRichMessageMedia] references such as
|
||||
* `tg://photo?id=...` and as typed blocks; [dev.inmo.tgbotapi.requests.send.SendRichMessage] also turns
|
||||
* multipart files inside an input tree into `attach://` uploads.
|
||||
* multipart files inside an input tree into `attach://` uploads. Bot API 10.3 button rows, inline rich-text buttons,
|
||||
* compact tables, expandable quotations and document blocks are demonstrated by `/rich_10_3` and the document
|
||||
* trigger. `/rich_quote` demonstrates nested expandable quotations, a TON address, and replying to a
|
||||
* user-selected passage using its rich texts and UTF-16 position.
|
||||
*
|
||||
* Incoming [dev.inmo.tgbotapi.types.message.content.RichMessageContent] and user-selected content covers
|
||||
* [onRichMessage], [waitRichMessage], [onlyRichMessageContentMessages], photo reuse, and
|
||||
@@ -332,7 +360,15 @@ suspend fun main(vararg args: String) {
|
||||
plain("\n")
|
||||
customEmoji(CustomEmojiId("5368324170671202286"), "👍")
|
||||
plain("\n")
|
||||
dateTime("22:45 tomorrow", TelegramDate(1647531900L), "wDT")
|
||||
dateTime(
|
||||
text = "22:45 tomorrow",
|
||||
unixTime = TelegramDate(1647531900L),
|
||||
dateTimeFormat = DateTimeEntityFormatting(
|
||||
useWeek = true,
|
||||
useDateLong = false,
|
||||
useTimeLong = false
|
||||
)
|
||||
)
|
||||
plain("\n")
|
||||
mathematicalExpression("x^2 + y^2")
|
||||
plain("\n#hashtag ${'$'}USD +12345678901, card: 4242 4242 4242 4242, https://t.me t.me a@t.me /command @username\n")
|
||||
@@ -692,20 +728,41 @@ suspend fun main(vararg args: String) {
|
||||
|
||||
// sendRichMessageDraft: stream partial rich messages sharing one draftId, then finalize
|
||||
// with a full sendRichMessage. Emulates streaming of an AI-generated reply.
|
||||
onCommand("rich_draft") {
|
||||
val chatId = it.chat.id.toChatId()
|
||||
val draftId = 1L
|
||||
onCommand("rich_draft", initialFilter = { it.chat is PrivateChat }) { origin ->
|
||||
val draftId = richDraftIds.allocate()
|
||||
val stoppedUpdate = async(start = CoroutineStart.UNDISPATCHED) {
|
||||
waitMessageGenerationStopped()
|
||||
.filter {
|
||||
it.sameChat(origin) && it.draftId == draftId
|
||||
}
|
||||
.first()
|
||||
}
|
||||
val parts = listOf(
|
||||
"Thinking",
|
||||
"Thinking about *rich* messages",
|
||||
"Thinking about *rich* messages and how to _stream_ them"
|
||||
)
|
||||
parts.forEach { part ->
|
||||
sendRichMessageDraft(chatId, draftId, InputRichMessageMarkdown(part))
|
||||
delay(1000)
|
||||
try {
|
||||
parts.forEach { part ->
|
||||
sendRichMessageDraft(
|
||||
origin.chat.id,
|
||||
draftId.long,
|
||||
InputRichMessageMarkdown(part),
|
||||
canStop = true,
|
||||
keepOnStop = true,
|
||||
)
|
||||
val stopped = withTimeoutOrNull(5000L) { stoppedUpdate.await() }
|
||||
if (stopped != null) {
|
||||
reply(origin, "Stopped rich draft ${stopped.draftId.long} in ${stopped.chat.id}")
|
||||
return@onCommand
|
||||
}
|
||||
}
|
||||
// Finalize only if the user did not stop generation; a normal message removes a retained draft.
|
||||
sendRichMessage(origin.chat.id, InputRichMessageMarkdown("Done! Here is the *final* rich message."))
|
||||
} finally {
|
||||
stoppedUpdate.cancel()
|
||||
richDraftIds.free(draftId)
|
||||
}
|
||||
// finalize the streamed draft with the real message
|
||||
sendRichMessage(chatId, InputRichMessageMarkdown("Done! Here is the *final* rich message."))
|
||||
}
|
||||
|
||||
// EditChatMessageRichText: send a rich message, then edit it with new rich content
|
||||
@@ -772,29 +829,187 @@ suspend fun main(vararg args: String) {
|
||||
)
|
||||
}
|
||||
|
||||
// sendRichMessageDraft with blocks: the thinking() block is only valid inside a draft and is used
|
||||
// to stream a model's reasoning before the finalized rich message is sent via sendRichMessage.
|
||||
onCommand("rich_blocks_draft") {
|
||||
val chatId = it.chat.id.toChatId()
|
||||
val draftId = 2L
|
||||
listOf("Analyzing your request", "Composing a structured answer").forEach { step ->
|
||||
sendRichMessageDraft(
|
||||
chatId,
|
||||
draftId,
|
||||
InputRichMessageBlocks { thinking(step) }
|
||||
)
|
||||
delay(1000)
|
||||
}
|
||||
// finalize the streamed draft with the real (non-thinking) blocks
|
||||
// === Bot API 10.3 additions: buttons, compact tables, expandable quotes and documents ===
|
||||
onCommand("rich_10_3") {
|
||||
val callbackButton = RichMessageButton.CallbackData(
|
||||
RichTextPlain("Callback"),
|
||||
callbackData = "rich_10_3_callback",
|
||||
style = RichMessageButtonStyle.Link,
|
||||
)
|
||||
sendRichMessage(
|
||||
chatId,
|
||||
it.chat.id,
|
||||
InputRichMessageBlocks {
|
||||
heading("Answer", level = 2)
|
||||
paragraph("Here is the finalized, structured reply.")
|
||||
h1("Bot API 10.3 rich blocks")
|
||||
paragraph {
|
||||
plain("A RichTextButton can live inline with text: ")
|
||||
button(
|
||||
RichMessageButton.CopyText(
|
||||
RichTextPlain("copy 42"),
|
||||
CopyTextButtonData("42"),
|
||||
style = RichMessageButtonStyle.Primary,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
expandableBlockQuotation(credit = RichTextPlain("Expandable quotation credit")) {
|
||||
plain("This quotation starts collapsed and can be expanded by the reader. ")
|
||||
dateTime("Bot API 10.3", TelegramDate(1787518800L), DateTimeEntityFormatting(useDateLong = true))
|
||||
}
|
||||
|
||||
table(
|
||||
isBordered = true,
|
||||
isStriped = true,
|
||||
isCompact = true,
|
||||
caption = RichTextPlain("A compact table"),
|
||||
) {
|
||||
row {
|
||||
headerCell(RichBlockTableCellAlign.Left, RichBlockTableCellVAlign.Middle) { plain("Feature") }
|
||||
headerCell(RichBlockTableCellAlign.Right, RichBlockTableCellVAlign.Middle) { plain("Version") }
|
||||
}
|
||||
row {
|
||||
cell(RichBlockTableCellAlign.Left, RichBlockTableCellVAlign.Middle) { plain("Compact tables") }
|
||||
cell(RichBlockTableCellAlign.Right, RichBlockTableCellVAlign.Middle) { plain("10.3") }
|
||||
}
|
||||
}
|
||||
|
||||
buttons(
|
||||
listOf(
|
||||
RichMessageButton.Url(
|
||||
RichTextPlain("Telegram"),
|
||||
"https://telegram.org",
|
||||
RichMessageButtonStyle.Primary,
|
||||
),
|
||||
callbackButton,
|
||||
),
|
||||
align = RichBlockButtonAlignment.Left,
|
||||
)
|
||||
buttons(
|
||||
listOf(
|
||||
RichMessageButton.SwitchInlineQuery(
|
||||
RichTextPlain("Choose chat"),
|
||||
"rich 10.3",
|
||||
RichMessageButtonStyle.Success,
|
||||
),
|
||||
RichMessageButton.SwitchInlineQueryCurrentChat(
|
||||
RichTextPlain("Current chat"),
|
||||
"rich 10.3",
|
||||
),
|
||||
RichMessageButton.SwitchInlineQueryChosenChat(
|
||||
RichTextPlain("Groups only"),
|
||||
SwitchInlineQueryChosenChat(
|
||||
query = "rich 10.3",
|
||||
allowGroups = true,
|
||||
),
|
||||
),
|
||||
),
|
||||
align = RichBlockButtonAlignment.Center,
|
||||
)
|
||||
buttons(
|
||||
listOf(
|
||||
RichMessageButton.CopyText(
|
||||
RichTextPlain("Copy value"),
|
||||
CopyTextButtonData("Bot API 10.3"),
|
||||
),
|
||||
RichMessageButton.Disabled(
|
||||
RichTextPlain("Disabled"),
|
||||
RichMessageButtonStyle.Danger,
|
||||
),
|
||||
),
|
||||
align = RichBlockButtonAlignment.Right,
|
||||
)
|
||||
|
||||
document(
|
||||
TelegramMediaDocument(
|
||||
InputFile.fromUrl("https://github.com/InsanusMokrassar/ktgbotapi/archive/refs/heads/master.zip"),
|
||||
),
|
||||
RichBlockCaption(RichTextPlain("A general-file document block")),
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
onDataCallbackQuery("rich_10_3_callback") { query ->
|
||||
answer(query, "Rich-message callback received")
|
||||
}
|
||||
|
||||
onCommand("rich_quote") { command ->
|
||||
val quote = command.content.quote
|
||||
val original = command.replyTo
|
||||
if (original != null && quote != null && !quote.richTexts.isNullOrEmpty()) {
|
||||
sendMessage(
|
||||
command.chat.id,
|
||||
"Your selection starts at UTF-16 offset ${quote.position}.",
|
||||
replyParameters = ReplyParameters(
|
||||
messageId = original.messageId,
|
||||
quoteRichTexts = quote.richTexts,
|
||||
quotePosition = quote.position,
|
||||
),
|
||||
)
|
||||
return@onCommand
|
||||
}
|
||||
|
||||
val zeroAddress = TonAddress("EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c")
|
||||
sendRichMessage(
|
||||
command.chat.id,
|
||||
InputRichMessageBlocks {
|
||||
paragraph("Expand the quotation, select a passage, and reply with /rich_quote.")
|
||||
expandableBlockQuotation(
|
||||
blocks = {
|
||||
paragraph { bold("📘 Sample address book") }
|
||||
unorderedList {
|
||||
item {
|
||||
paragraph {
|
||||
plain("The TON zero address is ")
|
||||
tonAddress(zeroAddress.value, zeroAddress)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
credit = RichTextPlain("Address book example"),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// sendRichMessageDraft with blocks: the thinking() block is only valid inside a draft and is used
|
||||
// to stream a model's reasoning before the finalized rich message is sent via sendRichMessage.
|
||||
onCommand("rich_blocks_draft", initialFilter = { it.chat is PrivateChat }) { origin ->
|
||||
val chatId = origin.chat.id.toChatId()
|
||||
val draftId = richDraftIds.allocate()
|
||||
val stoppedUpdate = async(start = CoroutineStart.UNDISPATCHED) {
|
||||
waitMessageGenerationStopped()
|
||||
.filter { it.chat.id == origin.chat.id && it.draftId == draftId }
|
||||
.first()
|
||||
}
|
||||
try {
|
||||
listOf("Analyzing your request", "Composing a structured answer").forEach { step ->
|
||||
sendRichMessageDraft(
|
||||
chatId,
|
||||
draftId.long,
|
||||
InputRichMessageBlocks { thinking(step) },
|
||||
canStop = true,
|
||||
keepOnStop = true,
|
||||
)
|
||||
val stopped = withTimeoutOrNull(1000L) { stoppedUpdate.await() }
|
||||
if (stopped != null) {
|
||||
println("Stopped rich block draft ${stopped.draftId.long} in ${stopped.chat.id}")
|
||||
return@onCommand
|
||||
}
|
||||
}
|
||||
// Finalize only if the user did not stop generation; a normal message removes a retained draft.
|
||||
sendRichMessage(
|
||||
chatId,
|
||||
InputRichMessageBlocks {
|
||||
heading("Answer", level = 2)
|
||||
paragraph("Here is the finalized, structured reply.")
|
||||
}
|
||||
)
|
||||
} finally {
|
||||
stoppedUpdate.cancel()
|
||||
richDraftIds.free(draftId)
|
||||
}
|
||||
}
|
||||
|
||||
// Rich message media: send me a photo and it gets embedded into a rich message two ways.
|
||||
onPhoto { message ->
|
||||
// reuse the received file by its fileId (no upload). To upload a brand-new file instead,
|
||||
@@ -828,6 +1043,40 @@ suspend fun main(vararg args: String) {
|
||||
)
|
||||
}
|
||||
|
||||
// A received document demonstrates both tg://document?id= references and a direct multipart upload.
|
||||
onDocument { message ->
|
||||
val reusedDocument = TelegramMediaDocument(message.content.media.fileId)
|
||||
sendRichMessage(
|
||||
message.chat.id,
|
||||
InputRichMessageHTML(
|
||||
"""
|
||||
<h2>Your document, referenced from HTML</h2>
|
||||
<tg-document src="tg://document?id=userdocument"></tg-document>
|
||||
""".trimIndent(),
|
||||
media = listOf(
|
||||
InputRichMessageMedia(id = "userdocument", media = reusedDocument)
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
val uploadedDocument = TelegramMediaDocument(
|
||||
downloadFile(message.content).asMultipartFile(
|
||||
message.content.media.fileName ?: "document.bin"
|
||||
)
|
||||
)
|
||||
sendRichMessage(
|
||||
message.chat.id,
|
||||
InputRichMessageBlocks {
|
||||
h2("Your document, uploaded as a new file")
|
||||
paragraph("SendRichMessage collects the MultipartFile nested in this document block.")
|
||||
document(
|
||||
uploadedDocument,
|
||||
RichBlockCaption(RichTextPlain("Direct attach:// document upload")),
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// waitRichMessage expectation: wait for the user to send a rich message
|
||||
onCommand("wait_rich") {
|
||||
reply(it, "Send me a rich message now")
|
||||
@@ -913,6 +1162,8 @@ suspend fun main(vararg args: String) {
|
||||
BotCommand("rich_html", "Send a rich message described with HTML"),
|
||||
BotCommand("rich_markdown", "Send a rich message described with Markdown"),
|
||||
BotCommand("rich_blocks", "Send a rich message built from the InputRichBlocks DSL"),
|
||||
BotCommand("rich_10_3", "Show Bot API 10.3 rich blocks and buttons"),
|
||||
BotCommand("rich_quote", "Select and quote a passage from a rich message"),
|
||||
BotCommand("rich_draft", "Stream a rich message draft, then finalize it"),
|
||||
BotCommand("rich_blocks_draft", "Stream a blocks draft with thinking(), then finalize it"),
|
||||
BotCommand("rich_edit", "Send a rich message and edit it with new rich content"),
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
# RightsChangerBot
|
||||
|
||||
A long-polling/FSM example for changing a member's chat permissions and a channel administrator's rights with inline keyboards. The bot registers its commands in the all-group-chats scope and prints every received update to standard output.
|
||||
A long-polling/FSM example for changing a member's chat permissions and a channel administrator's rights with inline keyboards. The group command menu lists `/simple`, `/granular`, and `/rights_in_channel`. The bot prints every received update to standard output.
|
||||
|
||||
## Commands and callbacks
|
||||
|
||||
### Linked verification descriptions
|
||||
|
||||
An approved third-party verifier bot can attach a text link to its verification description. Type
|
||||
`/verify <user_or_chat_id> <https_record_url>` in the allowed user's private chat with the bot.
|
||||
Use the numeric ID of a user or chat the bot can look up. The example calls `verifyChat` with the
|
||||
chat and a formatted description. For a private chat the library calls `verifyUser`. Telegram displays
|
||||
**Verification record** as a link to the supplied URL. The verifier needs permission to set a custom
|
||||
description. [Telegram verification API](https://core.telegram.org/bots/api#verifychat)
|
||||
|
||||
### Member permissions
|
||||
|
||||
Run these commands in a group or supergroup as a reply to a non-administrator's message:
|
||||
@@ -19,7 +28,7 @@ Send `/rights_in_channel` in a private chat with the bot. Telegram's chat/user r
|
||||
|
||||
1. Select a channel where the bot is already a member. The picker requests `can_promote_members` and `can_restrict_members` for both the bot and the selecting user.
|
||||
2. Select a user, or send `/cancel` during either selection step.
|
||||
3. If the selected user is currently a channel administrator, the bot sends a keyboard for refreshing or toggling post-message, edit-message, delete-message, post-story, edit-story, and delete-story rights.
|
||||
3. If the selected user is currently a channel administrator, the bot sends a keyboard for refreshing or toggling post-message, edit-message, delete-message, post-story, edit-story, delete-story, and Bot API 10.3's send-welcome-messages rights.
|
||||
|
||||
Selecting a non-administrator ends the flow without a message. A stale keyboard whose target is later demoted can display **Promote to admin**; that action promotes the target with the post-messages right enabled. Telegram allows the bot to change an administrator's rights only when the bot promoted that administrator itself.
|
||||
|
||||
@@ -29,7 +38,7 @@ Callbacks are processed only when clicked by the configured allowed user. They a
|
||||
|
||||
- Create a bot with [@BotFather](https://t.me/BotFather) and obtain its token.
|
||||
- Choose one trusted Telegram numeric user ID as `ALLOWED_USER_ID`. `/simple` and all permission-changing callbacks are restricted to this ID.
|
||||
- Promote the bot in managed groups/channels. It needs `can_restrict_members` for member permissions and `can_promote_members` for channel administrator rights, plus enough rights to read member state and send/edit its keyboard messages. It cannot grant rights it does not possess.
|
||||
- Promote the bot in managed groups/channels. It needs `can_restrict_members` for member permissions and `can_promote_members` for channel administrator rights, plus enough rights to read member state and send/edit its keyboard messages. To grant `can_send_welcome_messages`, the bot must possess that right itself. It cannot grant rights it does not possess.
|
||||
- BotFather privacy mode can remain enabled because the group workflows use commands, replies, and callbacks.
|
||||
- Treat console output as sensitive: the example prints every raw update, and handler failures print stack traces.
|
||||
|
||||
|
||||
@@ -11,12 +11,12 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="RightsChangerKt"
|
||||
application.mainClass = "RightsChangerKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
|
||||
|
||||
implementation "dev.inmo:tgbotapi:$telegram_bot_api_version"
|
||||
implementation 'io.ktor:ktor-client-logging-jvm:3.2.3'
|
||||
implementation "io.ktor:ktor-client-logging-jvm:$ktor_version"
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import dev.inmo.kslog.common.LogLevel
|
||||
import dev.inmo.kslog.common.defaultMessageFormatter
|
||||
import dev.inmo.kslog.common.setDefaultKSLog
|
||||
import dev.inmo.micro_utils.coroutines.firstOf
|
||||
import dev.inmo.micro_utils.coroutines.runCatchingLogging
|
||||
import dev.inmo.micro_utils.coroutines.subscribeSafelyWithoutExceptions
|
||||
import dev.inmo.micro_utils.fsm.common.State
|
||||
import dev.inmo.tgbotapi.bot.ktor.telegramBot
|
||||
@@ -14,48 +15,52 @@ import dev.inmo.tgbotapi.extensions.api.chat.members.restrictChatMember
|
||||
import dev.inmo.tgbotapi.extensions.api.edit.edit
|
||||
import dev.inmo.tgbotapi.extensions.api.send.reply
|
||||
import dev.inmo.tgbotapi.extensions.api.send.send
|
||||
import dev.inmo.tgbotapi.extensions.api.verifications.verifyChat
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.BehaviourContext
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.buildBehaviourWithFSMAndStartLongPolling
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitChatSharedEventsMessages
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitCommandMessage
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitUserSharedEventsMessages
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommand
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommandWithArgs
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onMessageDataCallbackQuery
|
||||
import dev.inmo.tgbotapi.extensions.utils.*
|
||||
import dev.inmo.tgbotapi.extensions.utils.extensions.raw.from
|
||||
import dev.inmo.tgbotapi.extensions.utils.extensions.sameChat
|
||||
import dev.inmo.tgbotapi.extensions.utils.types.buttons.*
|
||||
import dev.inmo.tgbotapi.types.*
|
||||
import dev.inmo.tgbotapi.types.buttons.InlineKeyboardMarkup
|
||||
import dev.inmo.tgbotapi.types.chat.ChannelChat
|
||||
import dev.inmo.tgbotapi.types.chat.ChatPermissions
|
||||
import dev.inmo.tgbotapi.types.chat.PrivateChat
|
||||
import dev.inmo.tgbotapi.types.chat.PublicChat
|
||||
import dev.inmo.tgbotapi.types.chat.member.AdministratorChatMember
|
||||
import dev.inmo.tgbotapi.types.chat.member.ChatCommonAdministratorRights
|
||||
import dev.inmo.tgbotapi.types.commands.BotCommandScope
|
||||
import dev.inmo.tgbotapi.types.message.abstracts.AccessibleMessage
|
||||
import dev.inmo.tgbotapi.types.message.abstracts.ChatMessage
|
||||
import dev.inmo.tgbotapi.types.request.RequestId
|
||||
import dev.inmo.tgbotapi.utils.*
|
||||
import kotlinx.coroutines.flow.filter
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.mapNotNull
|
||||
import kotlinx.coroutines.flow.merge
|
||||
|
||||
/** States used by the private-chat flow that selects a channel and one of its users. */
|
||||
sealed interface UserRetrievingStep : State {
|
||||
/** Waits for the user to share a channel in the private chat identified by [context]. */
|
||||
data class RetrievingChannelChatState(
|
||||
override val context: ChatId
|
||||
override val context: IdChatIdentifier
|
||||
) : UserRetrievingStep
|
||||
|
||||
/** Waits for a user selection after [channelId] has been shared. */
|
||||
data class RetrievingUserIdChatState(
|
||||
override val context: ChatId,
|
||||
override val context: IdChatIdentifier,
|
||||
val channelId: ChatId
|
||||
) : UserRetrievingStep
|
||||
|
||||
/** Carries the selected [channelId] and [userId] to the administrator-rights keyboard step. */
|
||||
data class RetrievingChatInfoDoneState(
|
||||
override val context: ChatId,
|
||||
override val context: IdChatIdentifier,
|
||||
val channelId: ChatId,
|
||||
val userId: UserId
|
||||
) : UserRetrievingStep
|
||||
@@ -116,6 +121,7 @@ suspend fun main(args: Array<String>) {
|
||||
val editStoriesToggleAdminRightsData = "${adminRightsDataPrefix}_edit_stories"
|
||||
val deleteStoriesToggleAdminRightsData = "${adminRightsDataPrefix}_delete_stories"
|
||||
val postStoriesToggleAdminRightsData = "${adminRightsDataPrefix}_post_stories"
|
||||
val sendWelcomeMessagesToggleAdminRightsData = "${adminRightsDataPrefix}_send_welcome_messages"
|
||||
|
||||
suspend fun BehaviourContext.getUserChatPermissions(chatId: ChatId, userId: UserId): ChatPermissions? {
|
||||
val chatMember = getChatMember(chatId, userId)
|
||||
@@ -182,6 +188,12 @@ suspend fun main(args: Array<String>) {
|
||||
row {
|
||||
dataButton("Post stories${permissions.canPostStories.allowedSymbol()}", "$postStoriesToggleAdminRightsData ${channelId.chatId} ${userId.chatId}")
|
||||
}
|
||||
row {
|
||||
dataButton(
|
||||
"Send welcome messages${permissions.canSendWelcomeMessages.allowedSymbol()}",
|
||||
"$sendWelcomeMessagesToggleAdminRightsData ${channelId.chatId} ${userId.chatId}"
|
||||
)
|
||||
}
|
||||
} ?: row {
|
||||
dataButton("Promote to admin", "$postMessagesToggleAdminRightsData ${channelId.chatId} ${userId.chatId}")
|
||||
}
|
||||
@@ -215,6 +227,23 @@ suspend fun main(args: Array<String>) {
|
||||
it.printStackTrace()
|
||||
},
|
||||
) {
|
||||
onCommandWithArgs(
|
||||
"verify",
|
||||
initialFilter = { it.chat is PrivateChat && it.fromUserMessageOrNull()?.user?.id == allowedAdmin }
|
||||
) { message, arguments ->
|
||||
val targetId = arguments.getOrNull(0)?.toLongOrNull()
|
||||
val recordUrl = arguments.getOrNull(1)
|
||||
if (arguments.size != 2 || targetId == null || recordUrl == null || !recordUrl.startsWith("https://")) {
|
||||
reply(message, "Usage: /verify <user_or_chat_id> <https_record_url>")
|
||||
return@onCommandWithArgs
|
||||
}
|
||||
val target = getChat(ChatId(RawChatId(targetId)))
|
||||
verifyChat(target, buildEntities {
|
||||
link("Verification record", recordUrl)
|
||||
})
|
||||
reply(message, "Verified ${target.id}.")
|
||||
}
|
||||
|
||||
onCommand(
|
||||
"simple",
|
||||
initialFilter = { it.chat is PublicChat && it.fromUserMessageOrNull()?.user?.id == allowedAdmin }
|
||||
@@ -240,13 +269,14 @@ suspend fun main(args: Array<String>) {
|
||||
}
|
||||
) {
|
||||
val replyMessage = it.replyTo
|
||||
val userInReply = replyMessage?.fromUserMessageOrNull()?.user?.id ?: return@onCommand
|
||||
val userInReply = replyMessage ?.from ?.id ?: return@onCommand
|
||||
|
||||
if (replyMessage is ChatMessage) {
|
||||
val keyboard = buildGranularKeyboard(it.chat.id.toChatId(), userInReply)
|
||||
reply(
|
||||
replyMessage,
|
||||
"Manage keyboard:",
|
||||
replyMarkup = buildGranularKeyboard(it.chat.id.toChatId(), userInReply) ?: return@onCommand
|
||||
replyMarkup = keyboard ?: return@onCommand
|
||||
)
|
||||
} else {
|
||||
reply(it) {
|
||||
@@ -415,6 +445,7 @@ suspend fun main(args: Array<String>) {
|
||||
canEditStories = asAdmin ?.canEditStories.toggleIfData(editStoriesToggleAdminRightsData),
|
||||
canDeleteStories = asAdmin ?.canDeleteStories.toggleIfData(deleteStoriesToggleAdminRightsData),
|
||||
canPostStories = asAdmin ?.canPostStories.toggleIfData(postStoriesToggleAdminRightsData),
|
||||
canSendWelcomeMessages = asAdmin ?.canSendWelcomeMessages.toggleIfData(sendWelcomeMessagesToggleAdminRightsData),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -477,7 +508,8 @@ suspend fun main(args: Array<String>) {
|
||||
}
|
||||
}
|
||||
strictlyOn<UserRetrievingStep.RetrievingUserIdChatState> { state ->
|
||||
val requestId = RequestId.random()
|
||||
val userRequestId = RequestId.random()
|
||||
val botRequestId = RequestId.random()
|
||||
send(
|
||||
state.context,
|
||||
replyMarkup = replyKeyboard(
|
||||
@@ -487,7 +519,11 @@ suspend fun main(args: Array<String>) {
|
||||
row {
|
||||
requestUserButton(
|
||||
"Choose user",
|
||||
requestId = requestId
|
||||
requestId = userRequestId
|
||||
)
|
||||
requestBotButton(
|
||||
"Choose bot",
|
||||
requestId = botRequestId
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -535,8 +571,8 @@ suspend fun main(args: Array<String>) {
|
||||
null
|
||||
}
|
||||
|
||||
onCommand("rights_in_channel") {
|
||||
startChain(UserRetrievingStep.RetrievingChannelChatState(it.chat.id.toChatId()))
|
||||
onCommand("rights_in_channel", initialFilter = { it.chat.privateChatOrNull() != null }) {
|
||||
startChain(UserRetrievingStep.RetrievingChannelChatState(it.chat.id))
|
||||
}
|
||||
|
||||
setMyCommands(
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="SlotMachineDetectorBotKt"
|
||||
application.mainClass = "SlotMachineDetectorBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# StarTransactionsBot
|
||||
|
||||
A long-polling Telegram Stars playground for invoices, transaction history, paid
|
||||
media, pre-checkout approval, and refund updates.
|
||||
A long-polling bot for Telegram Stars invoices, transaction history, paid media,
|
||||
refund updates, and TON wallet information.
|
||||
|
||||
## Commands
|
||||
|
||||
@@ -10,6 +10,9 @@ media, pre-checkout approval, and refund updates.
|
||||
automatically.
|
||||
- `/transactions` works only in the chat whose numeric ID was supplied as the
|
||||
second program argument. It replies with the bot's first transaction page.
|
||||
- `/wallet_card` in your private chat with the bot reads the public TON wallet card
|
||||
on your profile with `getChat`. It shows the wallet address, balance in the
|
||||
smallest units, and NFT sticker count, or reports that the card is absent.
|
||||
|
||||
The commands are not registered in Telegram's command menu.
|
||||
|
||||
@@ -34,6 +37,12 @@ Pagination state is encoded in callback data and is not persisted by the bot.
|
||||
paid media, retaining its caption above the media; only photos and videos are used.
|
||||
- Paid-media-info messages are printed to standard output.
|
||||
- Refunded-payment events receive a reply containing the payment information.
|
||||
- `onTonWalletTransfer` replies to a transfer service message with the signed
|
||||
amount, peer wallet address, and transaction ID. The amount stays in Telegram's
|
||||
decimal-string representation. Outgoing amounts are negative, and an empty
|
||||
transaction ID appears as pending.
|
||||
- `onPaidMessagesWaived` acknowledges the service message Telegram sends when
|
||||
someone uses a link that grants free messages to the recipient.
|
||||
- Every received update is printed to standard output.
|
||||
|
||||
## Setup, permissions, and payment safety
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="StarTransactionsBotKt"
|
||||
application.mainClass = "StarTransactionsBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -4,6 +4,7 @@ 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.payments.answerPreCheckoutQueryOk
|
||||
import dev.inmo.tgbotapi.extensions.api.chat.get.getChat
|
||||
import dev.inmo.tgbotapi.extensions.api.edit.edit
|
||||
import dev.inmo.tgbotapi.extensions.api.files.downloadFileToTemp
|
||||
import dev.inmo.tgbotapi.extensions.api.get.getStarTransactions
|
||||
@@ -11,6 +12,7 @@ import dev.inmo.tgbotapi.extensions.api.send.reply
|
||||
import dev.inmo.tgbotapi.extensions.api.send.send
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.telegramBotWithBehaviourAndLongPolling
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.*
|
||||
import dev.inmo.tgbotapi.extensions.utils.extendedPrivateChatOrNull
|
||||
import dev.inmo.tgbotapi.extensions.utils.extensions.sameChat
|
||||
import dev.inmo.tgbotapi.extensions.utils.types.buttons.*
|
||||
import dev.inmo.tgbotapi.extensions.utils.withContentOrNull
|
||||
@@ -19,6 +21,7 @@ import dev.inmo.tgbotapi.types.ChatId
|
||||
import dev.inmo.tgbotapi.types.RawChatId
|
||||
import dev.inmo.tgbotapi.types.UserId
|
||||
import dev.inmo.tgbotapi.types.buttons.InlineKeyboardMarkup
|
||||
import dev.inmo.tgbotapi.types.chat.PrivateChat
|
||||
import dev.inmo.tgbotapi.types.files.*
|
||||
import dev.inmo.tgbotapi.types.media.TelegramPaidMediaPhoto
|
||||
import dev.inmo.tgbotapi.types.media.TelegramPaidMediaVideo
|
||||
@@ -33,6 +36,7 @@ import dev.inmo.tgbotapi.utils.bold
|
||||
import dev.inmo.tgbotapi.utils.buildEntities
|
||||
import dev.inmo.tgbotapi.utils.regular
|
||||
import dev.inmo.tgbotapi.utils.row
|
||||
import dev.inmo.tgbotapi.utils.tonAddress
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
|
||||
@@ -42,8 +46,8 @@ import kotlinx.coroutines.Dispatchers
|
||||
* The first element of [args] must be the bot token and the second a numeric admin
|
||||
* user/chat ID authorized for `/transactions`. Optional exact values `debug` and
|
||||
* `testServer` enable diagnostic logging and Telegram's test environment. Other
|
||||
* handlers create a one-Star invoice or paid media and report payment-related
|
||||
* updates.
|
||||
* handlers display the current user's TON wallet card, report TON transfers and
|
||||
* free-message access, or create a one-Star invoice or paid media.
|
||||
*/
|
||||
suspend fun main(vararg args: String) {
|
||||
val botToken = args.first()
|
||||
@@ -79,6 +83,32 @@ suspend fun main(vararg args: String) {
|
||||
answerPreCheckoutQueryOk(it)
|
||||
}
|
||||
|
||||
onCommand("wallet_card", initialFilter = { it.chat is PrivateChat }) { message ->
|
||||
val card = getChat(message.chat.id).extendedPrivateChatOrNull()?.tonWalletCard
|
||||
if (card == null) {
|
||||
reply(message, "Your profile has no public TON wallet card.")
|
||||
return@onCommand
|
||||
}
|
||||
reply(message) {
|
||||
+"Wallet "
|
||||
tonAddress(card.address.value)
|
||||
+"\nBalance of ${card.amount} in the smallest units\n${card.stickers.size} NFT stickers"
|
||||
}
|
||||
}
|
||||
|
||||
onTonWalletTransfer { message ->
|
||||
val transfer = message.chatEvent
|
||||
reply(message) {
|
||||
+"TON transfer of ${transfer.amount} in the smallest units\nPeer wallet "
|
||||
tonAddress(transfer.peerAddress.value)
|
||||
+"\nTransaction ${transfer.transactionId.ifEmpty { "pending" }}"
|
||||
}
|
||||
}
|
||||
|
||||
onPaidMessagesWaived { message ->
|
||||
reply(message, "The sender used a link that grants free messages to this recipient.")
|
||||
}
|
||||
|
||||
val transactionsDataPrefix = "getStarTransactions"
|
||||
fun buildTransactionsData(offset: Int, limit: Int = 10) = "$transactionsDataPrefix $offset $limit"
|
||||
fun parseTransactionsData(data: String): Pair<Int, Int> = data.split(" ").drop(1).let {
|
||||
|
||||
@@ -30,7 +30,6 @@ The required first argument is the bot token. Additional arguments are ignored.
|
||||
./gradlew :StickerInfoBot:jvm_launcher:run --args="<BOT_TOKEN>"
|
||||
```
|
||||
|
||||
> **Known issue:** `jvm_launcher/build.gradle` declares `StickerInfoBotJvmKt`, while the current launcher filename produces `StickerInfoBotBotJvmKt`. The `run` task cannot start until that main-class setting is corrected; it is left unchanged by this documentation-only update.
|
||||
|
||||
The JVM launcher prints the startup `getMe` result, raw updates, and errors to standard output.
|
||||
|
||||
|
||||
@@ -15,8 +15,7 @@ plugins {
|
||||
|
||||
kotlin {
|
||||
jvm()
|
||||
// js(LEGACY) {
|
||||
js(IR) {
|
||||
js {
|
||||
browser()
|
||||
binaries.executable()
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="StickerInfoBotJvmKt"
|
||||
application.mainClass = "StickerInfoBotBotJvmKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="StickerSetHandlerBotKt"
|
||||
application.mainClass = "StickerSetHandlerBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="SuggestedPostsBotKt"
|
||||
application.mainClass = "SuggestedPostsBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="TagsBotKt"
|
||||
application.mainClass = "TagsBotKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -17,7 +17,8 @@ In a private chat, `/start_test_topics` first checks the bot's `has_topics_enabl
|
||||
The bot replies to these service events:
|
||||
|
||||
- forum topic created or edited;
|
||||
- private topic created or edited;
|
||||
- private topic created or edited. The creation reply includes a link that reopens the topic in the user's private
|
||||
chat with the bot when Telegram supplies the thread ID;
|
||||
- forum topic reopened;
|
||||
- General topic hidden or unhidden.
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="TopicsHandlingKt"
|
||||
application.mainClass = "TopicsHandlingKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -19,6 +19,8 @@ import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onGenera
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onGeneralForumTopicUnhidden
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onPrivateForumTopicCreated
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onPrivateForumTopicEdited
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.utils.botInfo
|
||||
import dev.inmo.tgbotapi.extensions.utils.formatting.link
|
||||
import dev.inmo.tgbotapi.extensions.utils.forumChatOrNull
|
||||
import dev.inmo.tgbotapi.extensions.utils.forumContentMessageOrNull
|
||||
import dev.inmo.tgbotapi.extensions.utils.privateChatOrNull
|
||||
@@ -193,8 +195,9 @@ suspend fun main(vararg args: String) {
|
||||
onForumTopicCreated {
|
||||
reply(it, "Topic has been created")
|
||||
}
|
||||
onPrivateForumTopicCreated {
|
||||
reply(it, "Private topic has been created")
|
||||
onPrivateForumTopicCreated { message ->
|
||||
val topicLink = message.chat.id.threadId?.let { thread -> botInfo()?.username?.link(thread) }
|
||||
reply(message, listOfNotNull("Private topic has been created", topicLink).joinToString("\n"))
|
||||
}
|
||||
|
||||
onForumTopicEdited {
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="UserChatSharedKt"
|
||||
application.mainClass = "UserChatSharedKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
+6
-3
@@ -16,6 +16,10 @@ plugins {
|
||||
id "org.jetbrains.compose" version "$compose_version"
|
||||
}
|
||||
|
||||
composeCompiler {
|
||||
targetKotlinPlatforms.set([org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType.js])
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvm {
|
||||
binaries {
|
||||
@@ -24,7 +28,7 @@ kotlin {
|
||||
}
|
||||
}
|
||||
}
|
||||
js(IR) {
|
||||
js {
|
||||
browser()
|
||||
binaries.executable()
|
||||
}
|
||||
@@ -35,13 +39,13 @@ kotlin {
|
||||
implementation kotlin('stdlib')
|
||||
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:$serialization_version"
|
||||
implementation "dev.inmo:tgbotapi.core:$telegram_bot_api_version"
|
||||
implementation compose.runtime
|
||||
}
|
||||
}
|
||||
|
||||
jsMain {
|
||||
dependencies {
|
||||
implementation "dev.inmo:tgbotapi.webapps:$telegram_bot_api_version"
|
||||
implementation compose.runtime
|
||||
implementation compose.web.core
|
||||
}
|
||||
}
|
||||
@@ -51,7 +55,6 @@ kotlin {
|
||||
implementation "dev.inmo:tgbotapi:$telegram_bot_api_version"
|
||||
implementation "dev.inmo:micro_utils.ktor.server:$micro_utils_version"
|
||||
implementation "io.ktor:ktor-server-cio:$ktor_version"
|
||||
implementation compose.desktop.currentOs
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ buildscript {
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
mainClassName="WebHooksKt"
|
||||
application.mainClass = "WebHooksKt"
|
||||
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# WidgetsBot
|
||||
|
||||
WidgetsBot sends an interactive die inside a Telegram message. Tap **Roll a die** to get a private answer with your result. The bot also saves the number in the widget so anyone viewing that message can see the last roll.
|
||||
|
||||
## Run
|
||||
|
||||
Create a bot with BotFather and open its private chat in a Telegram client that supports widgets. From the repository root, run the long-polling bot with its token. [BotFather](https://t.me/BotFather)
|
||||
|
||||
```bash
|
||||
./gradlew :WidgetsBot:run --args="<BOT_TOKEN>"
|
||||
```
|
||||
|
||||
The optional `debug` argument enables diagnostic logging. Telegram currently supports widgets in private chats with the bot in production. To try groups, forwards, or inline results, use a bot token and account created in Telegram's test environment and add `testServer` after the token. [Test account setup](https://core.telegram.org/bots/features#creating-a-bot-in-the-test-environment) · [Widget availability](https://core.telegram.org/bots/widgets#availability)
|
||||
|
||||
## Try the widgets
|
||||
|
||||
| Command | What to try |
|
||||
| --- | --- |
|
||||
| `/start` | Show the two widget commands. |
|
||||
| `/widget` | Send a die and tap it. Send a second one to see that each message keeps its own last roll in `chatData`. |
|
||||
| `/sharedwidget` | Send two messages showing the same die. Tap either one and watch both last-roll values change to match. On the test server, forward one and roll it from the forward. |
|
||||
|
||||
`sendWidget` creates the shared die with `isShared = true` and `allowQueries = true`. The bot reads `widget.id` from the returned message and passes it to `sendSharedWidget` for the second message.
|
||||
|
||||
To try inline mode, send `/setinline` to BotFather on the test server, select the bot, and enter a placeholder. In a private chat or group, type `@your_bot_username` followed by a space and select **Roll a die**. Each selected `InputWidgetMessageContent` starts a new die. [Telegram inline setup](https://core.telegram.org/bots/inline) · [Inline widgets](https://core.telegram.org/bots/widgets#inline-mode-widgets)
|
||||
|
||||
A tap in a bot-sent or inline message reaches `onWidgetQuery`. A tap in a forward of the shared die reaches `onSharedWidgetQuery`. The bot calls `answerWidgetQuery` for the tapping viewer, then writes the roll with `editMessageWidgetData` using either the chat and message IDs or the inline message ID. For a shared die it calls `editSharedWidgetData` with the widget ID. Open copies call `watchPublicData()` to refresh on Telegram's polling interval. The example requests a five-second interval when saving a shared roll. [Telegram widget guide](https://core.telegram.org/bots/widgets#requests-to-the-bot)
|
||||
@@ -0,0 +1,19 @@
|
||||
buildscript {
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
|
||||
}
|
||||
}
|
||||
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
application.mainClass = "WidgetsBotKt"
|
||||
|
||||
dependencies {
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
|
||||
implementation "dev.inmo:tgbotapi:$telegram_bot_api_version"
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import dev.inmo.kslog.common.KSLog
|
||||
import dev.inmo.kslog.common.LogLevel
|
||||
import dev.inmo.kslog.common.defaultMessageFormatter
|
||||
import dev.inmo.kslog.common.setDefaultKSLog
|
||||
import dev.inmo.tgbotapi.bot.TelegramBot
|
||||
import dev.inmo.tgbotapi.bot.exceptions.MessageIsNotModifiedException
|
||||
import dev.inmo.tgbotapi.extensions.api.answers.answerInlineQuery
|
||||
import dev.inmo.tgbotapi.extensions.api.answers.answerWidgetQuery
|
||||
import dev.inmo.tgbotapi.extensions.api.edit.widgets.editMessageWidgetData
|
||||
import dev.inmo.tgbotapi.extensions.api.edit.widgets.editSharedWidgetData
|
||||
import dev.inmo.tgbotapi.extensions.api.send.reply
|
||||
import dev.inmo.tgbotapi.extensions.api.send.sendSharedWidget
|
||||
import dev.inmo.tgbotapi.extensions.api.send.sendWidget
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.telegramBotWithBehaviourAndLongPolling
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onAnyInlineQuery
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommand
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onSharedWidgetQuery
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onWidgetQuery
|
||||
import dev.inmo.tgbotapi.types.InlineQueries.InlineQueryResult.InlineQueryResultArticle
|
||||
import dev.inmo.tgbotapi.types.InlineQueries.InputMessageContent.InputWidgetMessageContent
|
||||
import dev.inmo.tgbotapi.types.InlineQueryId
|
||||
import dev.inmo.tgbotapi.types.chat.ChatType
|
||||
import dev.inmo.tgbotapi.types.widgets.WidgetQuery
|
||||
import dev.inmo.tgbotapi.types.widgets.WidgetQuerySource
|
||||
import dev.inmo.tgbotapi.types.widgets.WidgetQueryType
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlin.random.Random
|
||||
|
||||
private suspend fun TelegramBot.rollDie(query: WidgetQuerySource) {
|
||||
if (query.type !is WidgetQueryType.Data || query.data != "roll") {
|
||||
answerWidgetQuery(query, "Unknown die action.")
|
||||
return
|
||||
}
|
||||
|
||||
val roll = Random.nextInt(1, 7).toString()
|
||||
answerWidgetQuery(query, "You rolled $roll.")
|
||||
|
||||
val widgetId = query.widgetId
|
||||
val original = query as? WidgetQuery
|
||||
val inlineMessageId = original?.inlineMessageId
|
||||
val chat = original?.chat
|
||||
val messageId = original?.messageId
|
||||
try {
|
||||
when {
|
||||
widgetId != null -> editSharedWidgetData(widgetId, publicData = roll, cacheTime = 5)
|
||||
inlineMessageId != null -> editMessageWidgetData(inlineMessageId, chatData = roll)
|
||||
chat != null && messageId != null -> editMessageWidgetData(chat, messageId, chatData = roll)
|
||||
}
|
||||
} catch (_: MessageIsNotModifiedException) {
|
||||
// Two consecutive rolls can have the same value. The widget already shows it.
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun main(vararg args: String) {
|
||||
val botToken = requireNotNull(args.firstOrNull()) { "Pass the bot token as the first argument." }
|
||||
val isTestServer = "testServer" in args
|
||||
if ("debug" in args) {
|
||||
setDefaultKSLog(
|
||||
KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->
|
||||
println(defaultMessageFormatter(level, tag, message, throwable))
|
||||
}
|
||||
)
|
||||
}
|
||||
val dieHtml = checkNotNull(Thread.currentThread().contextClassLoader.getResource("die.html")).readText()
|
||||
val messageDie = InputWidgetMessageContent(
|
||||
html = dieHtml,
|
||||
chatData = "No rolls yet",
|
||||
allowQueries = true,
|
||||
text = "Roll this die to update its last roll in this message."
|
||||
)
|
||||
val inlineDie = InlineQueryResultArticle(
|
||||
id = InlineQueryId("die"),
|
||||
title = "Roll a die",
|
||||
inputMessageContent = messageDie
|
||||
)
|
||||
|
||||
telegramBotWithBehaviourAndLongPolling(
|
||||
botToken,
|
||||
CoroutineScope(Dispatchers.IO),
|
||||
testServer = isTestServer
|
||||
) {
|
||||
onCommand("start") {
|
||||
reply(it, "Use /widget for a die in one message or /sharedwidget to roll the same die in two messages.")
|
||||
}
|
||||
onCommand("widget") { message ->
|
||||
sendWidget(message.chat, messageDie)
|
||||
}
|
||||
onCommand("sharedwidget") { message ->
|
||||
val first = sendWidget(
|
||||
message.chat,
|
||||
html = dieHtml,
|
||||
publicData = "No rolls yet",
|
||||
allowQueries = true,
|
||||
isShared = true,
|
||||
text = "This die shares its last roll with every copy."
|
||||
)
|
||||
val widgetId = checkNotNull(first.content.widget.id) { "Telegram did not return a shared widget ID." }
|
||||
sendSharedWidget(message.chat, widgetId, text = "Roll here and watch the other message update.")
|
||||
}
|
||||
onAnyInlineQuery { query ->
|
||||
val results = if (isTestServer && query.chatType != ChatType.Channel) {
|
||||
listOf(inlineDie)
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
answerInlineQuery(query, results, cachedTime = 0)
|
||||
}
|
||||
|
||||
onWidgetQuery { rollDie(it) }
|
||||
onSharedWidgetQuery { rollDie(it) }
|
||||
}.second.join()
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<body>
|
||||
<h3>Last roll</h3>
|
||||
<p id="last-roll">No rolls yet</p>
|
||||
<button id="roll" disabled>Roll a die</button>
|
||||
<p id="answer"></p>
|
||||
<script>
|
||||
const widget = window.TelegramWidget;
|
||||
if (widget) {
|
||||
const lastRoll = document.getElementById('last-roll');
|
||||
const button = document.getElementById('roll');
|
||||
const answer = document.getElementById('answer');
|
||||
|
||||
function render() {
|
||||
lastRoll.textContent = widget.chatData || widget.publicData || 'No rolls yet';
|
||||
}
|
||||
|
||||
widget.onEvent('chatDataChanged', render);
|
||||
widget.onEvent('publicDataChanged', render);
|
||||
widget.watchPublicData();
|
||||
render();
|
||||
|
||||
button.disabled = !widget.viewer;
|
||||
button.addEventListener('click', () => {
|
||||
button.disabled = true;
|
||||
widget.request('roll').then(
|
||||
response => { answer.textContent = response.result; },
|
||||
error => { answer.textContent = 'Roll failed (' + error.code + ').'; }
|
||||
).finally(() => { button.disabled = false; });
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+1
-6
@@ -14,6 +14,7 @@ allprojects {
|
||||
nativePartTemplate = "${rootProject.projectDir.absolutePath}/native_template.gradle"
|
||||
}
|
||||
repositories {
|
||||
mavenLocal()
|
||||
mavenCentral()
|
||||
google()
|
||||
if (project.hasProperty("GITHUB_USER") && project.hasProperty("GITHUB_TOKEN")) {
|
||||
@@ -27,11 +28,5 @@ allprojects {
|
||||
}
|
||||
|
||||
maven { url "https://nexus.inmo.dev/repository/maven-releases/" }
|
||||
mavenLocal()
|
||||
}
|
||||
}
|
||||
|
||||
// Fix of https://youtrack.jetbrains.com/issue/KTOR-7912/Module-not-found-errors-when-executing-browserProductionWebpack-task-since-3.0.2
|
||||
rootProject.plugins.withType(org.jetbrains.kotlin.gradle.targets.js.yarn.YarnPlugin.class) {
|
||||
rootProject.kotlinYarn.resolution("ws", "8.18.0")
|
||||
}
|
||||
+6
-6
@@ -5,9 +5,9 @@ org.gradle.jvmargs=-Xmx3148m
|
||||
kotlin.daemon.jvmargs=-Xmx3g -Xms500m
|
||||
|
||||
|
||||
kotlin_version=2.3.20
|
||||
telegram_bot_api_version=36.0.0
|
||||
micro_utils_version=0.29.1
|
||||
serialization_version=1.10.0
|
||||
ktor_version=3.4.1
|
||||
compose_version=1.10.2
|
||||
kotlin_version=2.4.21
|
||||
telegram_bot_api_version=38.0.0-t1
|
||||
micro_utils_version=0.32.0
|
||||
serialization_version=1.11.0
|
||||
ktor_version=3.6.0
|
||||
compose_version=1.12.1
|
||||
Vendored
BIN
Binary file not shown.
+3
-1
@@ -1,5 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.0-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
|
||||
@@ -1,78 +1,129 @@
|
||||
#!/usr/bin/env sh
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS=""
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
}
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
@@ -81,92 +132,120 @@ Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=$((i+1))
|
||||
done
|
||||
case $i in
|
||||
(0) set -- ;;
|
||||
(1) set -- "$args0" ;;
|
||||
(2) set -- "$args0" "$args1" ;;
|
||||
(3) set -- "$args0" "$args1" "$args2" ;;
|
||||
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=$(save "$@")
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
|
||||
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
|
||||
cd "$(dirname "$0")"
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
+44
-34
@@ -1,4 +1,22 @@
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@@ -9,25 +27,29 @@
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS=
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto init
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
@@ -35,48 +57,36 @@ goto fail
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto init
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:init
|
||||
@rem Get command-line arguments, handling Windows variants
|
||||
|
||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
||||
|
||||
:win9xME_args
|
||||
@rem Slurp the command line arguments.
|
||||
set CMD_LINE_ARGS=
|
||||
set _SKIP=2
|
||||
|
||||
:win9xME_args_slurp
|
||||
if "x%~1" == "x" goto execute
|
||||
|
||||
set CMD_LINE_ARGS=%*
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
@@ -87,3 +87,5 @@ include ":EphemeralMessagesBot"
|
||||
include ":CommunitiesBot"
|
||||
|
||||
include ":BotSubscriptionsBot"
|
||||
|
||||
include ":WidgetsBot"
|
||||
Reference in new issue
Block a user