Compare commits

..
Author SHA1 Message Date
renovate[bot] f547bd3aa6 Update Gradle to v9 2026-11-20 04:16:45 +00:00
86 changed files with 279 additions and 689 deletions

No files matched your search

+3 -3
View File
@@ -11,12 +11,12 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "{{$title}}Kt"
description = "{{$subtitle}}"
mainClassName="{{$title}}Kt"
{{$subtitle}}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "dev.inmo:tgbotapi:$telegram_bot_api_version"
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "BoostsInfoKt"
mainClassName="BoostsInfoKt"
dependencies {
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "BotSubscriptionsBotKt"
mainClassName="BotSubscriptionsBotKt"
dependencies {
+2 -4
View File
@@ -22,7 +22,6 @@ 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` |
@@ -59,7 +58,7 @@ The inline **Read message** button calls `readBusinessMessage`. **Delete message
## Private-chat commands
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.
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.
| Command | Behavior |
| --- | --- |
@@ -68,8 +67,7 @@ Send these commands from the connected account owner's private chat with the bot
| `/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` | 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. |
| `/get_business_account_gifts` | Fetches every page of owned gifts and prints their Kotlin representations, splitting long output across messages. |
| `/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. |
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "BusinessConnectionsBotKt"
mainClassName="BusinessConnectionsBotKt"
dependencies {
@@ -3,10 +3,9 @@ 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.bot.exceptions.BotException
import dev.inmo.tgbotapi.types.chat.PreviewBot
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
@@ -42,28 +41,23 @@ 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
@@ -330,51 +324,14 @@ suspend fun main(args: Array<String>) {
}
} else {
giftsFlow.collect { giftsPage ->
giftsPage.gifts.joinToString("\n\n") { gift ->
buildString {
gift.ownedGiftId?.let { appendLine("Owned gift ID ${it.string}") }
append(gift)
}
giftsPage.gifts.joinToString {
it.toString()
}.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()
@@ -506,7 +463,7 @@ suspend fun main(args: Array<String>) {
activePeriod = PostStory.ACTIVE_PERIOD_6_HOURS,
areas = listOf(
StoryArea(
AreaPosition(
StoryAreaPosition(
x = Percentage.of100(50.0),
y = Percentage.of100(50.0),
width = Percentage.of100(8.0),
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "ChatAvatarSetterKt"
mainClassName="ChatAvatarSetterKt"
dependencies {
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "ChatManagementBotKt"
mainClassName="ChatManagementBotKt"
dependencies {
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "ChecklistsBotKt"
mainClassName="ChecklistsBotKt"
dependencies {
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "CommunitiesBotKt"
mainClassName="CommunitiesBotKt"
dependencies {
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "CustomBotKt"
mainClassName="CustomBotKt"
dependencies {
-5
View File
@@ -8,11 +8,6 @@ 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
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "DeepLinksBotKt"
mainClassName="DeepLinksBotKt"
dependencies {
@@ -1,20 +1,12 @@
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
/**
@@ -48,32 +40,6 @@ 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")
}
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "DraftsBotKt"
mainClassName="DraftsBotKt"
dependencies {
+16 -21
View File
@@ -1,33 +1,31 @@
# EphemeralMessagesBot
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.
Demonstrates Telegram Bot API 10.2 and 10.3 ephemeral messages: group messages that Telegram shows only to one receiver.
## Behavior
- `/ephemeral` replies with a **Reveal a secret** inline button. The command is registered with Telegram as
an ephemeral command.
- 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
- Pressing the button (`reveal` callback data) uses `EphemeralMessageParameters` to replace the callback-query
message with a personal rich message visible only to the user who pressed it. After three seconds the bot replaces
its text with typed rich blocks, then deletes it three seconds later.
- `/ephemeral_photo` waits for a photo from the same user and chat, sends it back ephemerally by its Telegram file ID,
downloads it, and edits the ephemeral media using a new multipart upload. A second edit sets
`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.
- `/ephemeral_live_photo` waits for a Live Photo, sends it ephemerally by existing file IDs, then downloads and
re-uploads both its main file and secondary `photo` file in one `editEphemeralMessageMedia` request. This exercises
ktgbotapi 37.0.0's secondary multipart attachment collection.
- When the bot receives an ephemeral content message, it sends two ephemeral replies: one through the
general `reply` API and one through the explicit `replyToEphemeral` API. The explicit form also uses
`EphemeralMessageParameters`.
- Updates and basic bot information are printed to standard output.
## Setup
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.
Create a bot token, keep it secret, and add the bot to a group. The bot must be allowed to send messages
there; this example does not request or validate group permissions itself. Use a Telegram environment that
supports ephemeral messages. The photo demonstrations download all selected media into memory before uploading it
again.
## Run
@@ -41,9 +39,6 @@ Optional, case-sensitive arguments may follow the token:
- `debug` enables formatted library logging on standard output.
- `testServer` connects the bot to Telegram's test server.
- `inlineCallbacks` calls `setMySettings` so that buttons in bot-sent messages produce callbacks with
an inline message ID. Run `/ephemeral` and press its button to try this delivery mode. The setting
persists until you change it. Use `defaultCallbacks` on a later launch to restore Telegram's default.
For example:
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "EphemeralMessagesBotKt"
mainClassName="EphemeralMessagesBotKt"
dependencies {
@@ -3,10 +3,8 @@ import dev.inmo.kslog.common.LogLevel
import dev.inmo.kslog.common.defaultMessageFormatter
import dev.inmo.kslog.common.setDefaultKSLog
import dev.inmo.micro_utils.coroutines.subscribeSafelyWithoutExceptions
import dev.inmo.tgbotapi.extensions.api.answers.answer
import dev.inmo.tgbotapi.extensions.api.bot.getMe
import dev.inmo.tgbotapi.extensions.api.bot.setMyCommands
import dev.inmo.tgbotapi.extensions.api.bot.setMySettings
import dev.inmo.tgbotapi.extensions.api.deleteEphemeralMessage
import dev.inmo.tgbotapi.extensions.api.edit.caption.editEphemeralMessageCaption
import dev.inmo.tgbotapi.extensions.api.edit.media.editEphemeralMessageMedia
@@ -22,20 +20,23 @@ import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitPhotoMess
import dev.inmo.tgbotapi.extensions.behaviour_builder.telegramBotWithBehaviourAndLongPolling
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommand
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onContentMessage
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onDataCallbackQuery
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onMessageDataCallbackQuery
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.EphemeralMessageParameters
import dev.inmo.tgbotapi.types.directMessageThreadIdOrMessageThreadIdAsDirectMessageThreadId
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
@@ -43,7 +44,7 @@ import kotlinx.coroutines.flow.first
/**
* Runs the ephemeral-messages example bot using long polling.
*
* `/ephemeral` posts an inline button whose callback sends a separate rich message visible only to
* `/ephemeral` posts an inline button whose callback replaces it with a 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
@@ -71,10 +72,6 @@ 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")
@@ -90,37 +87,47 @@ suspend fun main(vararg args: String) {
)
}
// Telegram resolves the destination from the callback, including callbacks carrying an inline message ID.
onDataCallbackQuery("reveal") { query ->
// Bot API 10.3 groups the recipient/callback fields in EphemeralMessageParameters. Setting
// replaceCallbackQueryMessage replaces the button message only for the user who pressed it.
onMessageDataCallbackQuery(Regex("reveal")) { query ->
val chatId = query.message.chat.id
val receiverUserId = query.from.id
val sent = sendRichMessage(
callbackQueryId = query.id,
richMessage = InputRichMessageBlocks {
chatId,
InputRichMessageBlocks {
paragraph {
plain("🔒 ${query.from.firstName}, here is your personal secret: ")
code("42")
}
},
replaceCallbackQueryMessage = false,
ephemeralMessageParameters = EphemeralMessageParameters(
receiverUserId = receiverUserId,
callbackQueryId = query.id,
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
?: 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)
if (ephemeralMessageId != null) {
delay(3.seconds)
// editEphemeralMessageText now accepts rich_message; the typed extension exposes that as
// editEphemeralMessageRichText.
editEphemeralMessageRichText(
chatId,
receiverUserId,
ephemeralMessageId,
InputRichMessageBlocks {
h2("Secret revealed")
paragraph { plain("The answer is "); code("42") }
},
)
delay(3.seconds)
// deleteEphemeralMessage: same addressing (there is also a PossiblyEphemeralMessage overload)
deleteEphemeralMessage(chatId, receiverUserId, ephemeralMessageId)
}
}
// Upload a received photo again as a brand-new multipart file while editing an ephemeral media message.
@@ -135,7 +142,7 @@ suspend fun main(vararg args: String) {
photoMessage.chat.id,
photoMessage.content.media.fileId,
text = "Ephemeral photo using its existing Telegram file ID",
receiverUserId = receiverUserId,
ephemeralMessageParameters = EphemeralMessageParameters(receiverUserId),
)
val ephemeralMessageId = (sent as? PossiblyEphemeralMessage)?.ephemeralMessageId
?: return@onCommand
@@ -173,7 +180,7 @@ suspend fun main(vararg args: String) {
chatId = livePhotoMessage.chat.id,
livePhoto = livePhoto,
text = "Ephemeral Live Photo using existing Telegram file IDs",
receiverUserId = receiverUserId,
ephemeralMessageParameters = EphemeralMessageParameters(receiverUserId),
)
val ephemeralMessageId = (sent as? PossiblyEphemeralMessage)?.ephemeralMessageId
?: return@onCommand
@@ -196,19 +203,23 @@ suspend fun main(vararg args: String) {
// Incoming ephemeral messages: detect them via PossiblyEphemeralMessage, then answer them.
onContentMessage { message ->
val ephemeralMessageId = (message as? PossiblyEphemeralMessage)?.ephemeralMessageId
val ephemeral = (message as? PossiblyEphemeralMessage)?.takeIf { it.ephemeralMessageId != null }
?: return@onContentMessage
val receiverUserId = message.ephemeralReplyReceiverUserIdOrNull ?: return@onContentMessage
// reply derives the receiver and ephemeral message ID from the incoming message.
// reply smart-branch: because `message` is ephemeral, this reply is sent ephemeral to the same
// receiver automatically — no ephemeral parameters needed here.
reply(message, "Got your ephemeral message — I am replying ephemerally too.")
replyToEphemeral(
chatId = message.chat.id,
receiverUserId = receiverUserId,
ephemeralMessageId = ephemeralMessageId,
text = "Explicit ephemeral reply via replyToEphemeral",
)
// The explicit equivalent, addressing the ephemeral message by hand:
val receiverUserId = ephemeral.ephemeralReplyReceiverUserIdOrNull
if (receiverUserId != null) {
replyToEphemeral(
message.chat.id,
EphemeralMessageParameters(receiverUserId),
ephemeral.ephemeralMessageId!!,
"Explicit ephemeral reply via replyToEphemeral",
)
}
}
setMyCommands(
+1 -1
View File
@@ -12,7 +12,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "SimpleFSMBotKt"
mainClassName="SimpleFSMBotKt"
repositories {
mavenLocal()
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "FilesLoaderBotKt"
mainClassName="FilesLoaderBotKt"
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "ForwardInfoSenderBotKt"
mainClassName="ForwardInfoSenderBotKt"
dependencies {
+4 -7
View File
@@ -1,6 +1,6 @@
# GiftsBot
Lists gifts owned by the current chat and looks up individual collectible gifts by name.
Demonstrates the paginated owned-gift APIs by listing gifts for the chat in which the command is received.
## Behavior
@@ -19,13 +19,10 @@ The bot also handles `UniqueGiftInfo` service messages with `onUniqueGiftSentOrR
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
## Command
- `/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 ordinary non-command messages are ignored; unique-gift service messages are handled separately.
@@ -37,8 +34,8 @@ Other commands and ordinary non-command messages are ignored; unique-gift servic
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 lookup reports Telegram's error description when available. The owned-gift listing requires the applicable chat
or business access.
The example performs no access checks or error recovery, so Telegram API or permission errors end that command
handler.
## Arguments and launch
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "GiftsBotKt"
mainClassName="GiftsBotKt"
dependencies {
+1 -25
View File
@@ -2,24 +2,20 @@ 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.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
@@ -28,7 +24,7 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
/**
* Lists owned gifts with `/start` and looks up an individual collectible by name with `/unique_gift`.
* Starts a long-polling bot whose standalone `/start` command lists all owned gifts for the current chat.
*
* 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
@@ -58,26 +54,6 @@ 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(
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "GiveawaysBotKt"
mainClassName="GiveawaysBotKt"
dependencies {
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "GuestQueryBotKt"
mainClassName="GuestQueryBotKt"
dependencies {
+3 -2
View File
@@ -5,8 +5,9 @@ message addresses the bot by username.
## Trigger and replies
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.
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.
- 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
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "HelloBotKt"
mainClassName="HelloBotKt"
dependencies {
+1 -4
View File
@@ -32,11 +32,8 @@ suspend fun main(vararg args: String) {
telegramBotWithBehaviourAndLongPolling(botToken, CoroutineScope(Dispatchers.IO)) {
val me = getMe()
val usernames = listOfNotNull(me.username) + me.activeUsernames
onContentMessage(
initialFilter = { message ->
usernames.any { message.text?.contains(it.full, ignoreCase = true) == true }
}
initialFilter = initialFilter@{ it.text ?.contains(me.username ?.full ?: return@initialFilter false) == true }
) { message ->
val answerText = when (val chat = message.chat) {
is PreviewChannelChat -> {
+5 -9
View File
@@ -17,9 +17,11 @@ The bot also prints its own account information at startup, logs received update
## Setup
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.
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.
## Launch from the repository root
@@ -29,12 +31,6 @@ need the token. You can also enable inline mode through BotFather.
./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,7 +1,6 @@
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
@@ -17,14 +16,8 @@ import dev.inmo.tgbotapi.utils.buildEntities
/**
* Starts the inline-query bot with [token] and suspends until long polling stops.
*/
suspend fun doInlineQueriesBot(token: String, configureInline: Boolean = false) {
suspend fun doInlineQueriesBot(token: String) {
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(), configureInline = "configureInline" in args)
doInlineQueriesBot(args.first())
}
@@ -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(), configureInline = "configureInline" in args)
doInlineQueriesBot(args.first())
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "JoinRequestQueriesBotKt"
mainClassName="JoinRequestQueriesBotKt"
dependencies {
+1 -1
View File
@@ -15,7 +15,7 @@ plugins {
kotlin {
jvm()
js {
js(IR) {
browser()
binaries.executable()
}
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "KeyboardsBotJvmKt"
mainClassName="KeyboardsBotJvmKt"
dependencies {
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "LinkPreviewsBotKt"
mainClassName="LinkPreviewsBotKt"
dependencies {
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "LiveLocationsBotKt"
mainClassName="LiveLocationsBotKt"
dependencies {
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "LivePhotosBotKt"
mainClassName="LivePhotosBotKt"
dependencies {
+5 -1
View File
@@ -39,7 +39,7 @@ No chat-administrator permission is requested by the code.
## Run
Run from the repository root:
The intended command from the repository root is:
```bash
./gradlew :ManagedBotsBot:run --args="BOT_TOKEN"
@@ -47,3 +47,7 @@ Run from the repository root:
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.
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "ManagedBotsBotKt"
mainClassName="CustomBotKt"
dependencies {
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "MemberUpdatedWatcherKt"
mainClassName="MemberUpdatedWatcherKt"
dependencies {
+5 -4
View File
@@ -4,8 +4,7 @@ A long-polling example that prints information about the bot and lets Telegram u
## Behavior
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:
At startup, the application prints the results of `getMe` and `getChat` for the bot itself to standard output. 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.
@@ -25,13 +24,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` runs the startup diagnostics and polling against Telegram's Bot API test environment.
- `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.
Other arguments are ignored. Argument matching is case-sensitive.
## Launch
Run from the repository root:
The intended command from the repository root is:
```bash
./gradlew :MyBot:run --args="<BOT_TOKEN>"
@@ -42,3 +41,5 @@ 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
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "MyBotKt"
mainClassName="GetMeBotKt"
dependencies {
+5 -2
View File
@@ -4,6 +4,7 @@ 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
@@ -46,14 +47,16 @@ suspend fun main(vararg args: String) {
)
}
val bot = telegramBot(botToken)
telegramBotWithBehaviourAndLongPolling(
botToken,
CoroutineScope(Dispatchers.Default),
testServer = isTestServer,
) {
val me = getMe()
val me = bot.getMe()
println(me)
println(getChat(me.id))
println(bot.getChat(me))
onCommand("setMyProfilePhoto") { commandMessage ->
reply(commandMessage, "ok, send me new photo")
+5 -1
View File
@@ -43,7 +43,7 @@ chat and client that support them.
## Run
Run from the repository root:
The intended command from the repository root is:
```bash
./gradlew :PollsBot:run --args="BOT_TOKEN"
@@ -51,3 +51,7 @@ Run from the repository root:
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.
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "PollsBotKt"
mainClassName="HelloBotKt"
dependencies {
+16 -23
View File
@@ -1,20 +1,12 @@
# TelegramBotAPI examples
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.
Runnable examples for [TelegramBotAPI](https://github.com/InsanusMokrassar/TelegramBotAPI), currently targeting tgbotapi 37.0.0 and Telegram Bot API 10.3. Each module focuses on a small Telegram Bot API feature and has its own README with detailed behavior, setup, permissions, and optional 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 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)
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`.
Native targets on Linux require libcurl development files, for example:
@@ -28,40 +20,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, including deletion of regular gifts by owned ID. | `./gradlew :BusinessConnectionsBot:run --args="<BOT_TOKEN> debug"` |
| [BusinessConnectionsBot](BusinessConnectionsBot/) | Manages a connected Business account, messages, Stars, gifts, stories, and checklists. | `./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 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 deep links and owner invitations, handles start payloads, and inspects chat share themes. | `./gradlew :DeepLinksBot:run --args="<BOT_TOKEN>"` |
| [DeepLinksBot](DeepLinksBot/) | Generates bot deep links and consumes their start payloads. | `./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"` |
| [EphemeralMessagesBot](EphemeralMessagesBot/) | Sends, replaces, and edits rich, photo, or Live Photo ephemeral messages. | `./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/) | Lists owned gifts, looks up unique gifts by name, and displays gift events. | `./gradlew :GiftsBot:run --args="<BOT_TOKEN> debug testServer"` |
| [GiftsBot](GiftsBot/) | Lists owned gifts and renders unique-gift service-message metadata. | `./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/) | Configures inline mode, answers paginated queries, and supplies a deep-link result. | `./gradlew :InlineQueriesBot:runJvm --args="<BOT_TOKEN>"` |
| [InlineQueriesBot](InlineQueriesBot/) | Answers inline 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, 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, 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"` |
| [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/) | 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"` |
| [RichMessagesBot](RichMessagesBot/) | Demonstrates rich markup/blocks, buttons, documents, drafts, queries, and media. | `./gradlew :RichMessagesBot:run --args="<BOT_TOKEN> debug testServer"` |
| [RightsChangerBot](RightsChangerBot/) | Uses an FSM and inline keyboards to change member and administrator rights, including welcome messages. | `./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/) | 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>"` |
| [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>"` |
| [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"` |
@@ -69,7 +61,8 @@ 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"` |
| [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"` |
† 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.
## Repository as a reference
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "ReactionsInfoBotKt"
mainClassName="ReactionsInfoBotKt"
dependencies {
+2 -2
View File
@@ -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, quote entities, rich-text
selections, their UTF-16 position, and the message effect ID.
present, it carries over the replied-to message metadata, text quote entities and
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
+2 -1
View File
@@ -15,7 +15,8 @@ plugins {
kotlin {
jvm()
js {
// js(LEGACY) {
js(IR) {
browser()
binaries.executable()
}
@@ -9,9 +9,10 @@ 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
@@ -48,13 +49,11 @@ suspend fun activateResenderBot(
it.content.createResend(
chat.id,
replyParameters = it.replyInfo?.messageMeta?.let { meta ->
val quote = (it.content as? WithOptionalQuoteInfo)?.quote
?: return@let ReplyParameters(meta)
val quote = it.withContentOrNull<TextContent>()?.content?.quote
ReplyParameters(
meta,
entities = quote.textSources,
quotePosition = quote.position,
quoteRichTexts = quote.richTexts
entities = quote?.textSources ?: emptyList(),
quotePosition = quote?.position
)
},
effectId = it.possiblyWithEffectMessageOrNull()?.effectId
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "ResenderBotJvmKt"
mainClassName="ResenderBotJvmKt"
dependencies {
+6 -12
View File
@@ -1,14 +1,15 @@
# RichMessagesBot
RichMessagesBot is a long-polling showcase of Telegram rich messages. It sends
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.
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. Bot API 10.3 coverage includes rich
buttons, compact tables, expandable quotations, document blocks, document
references, direct document uploads, and stoppable drafts.
## Commands
The bot installs nine commands in Telegram's default command menu. Three
The bot installs eight commands in Telegram's default command menu. Three
additional handlers can be invoked by typing their commands manually.
| Command | In menu | Demonstration |
@@ -20,18 +21,11 @@ additional handlers can be invoked by typing their commands manually.
| `/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_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. |
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;
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "RichMessagesBotKt"
mainClassName="RichMessagesBotKt"
dependencies {
@@ -7,7 +7,6 @@ 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
@@ -15,9 +14,9 @@ import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitRichMessa
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.onMessageDataCallbackQuery
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
@@ -34,7 +33,6 @@ 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
@@ -45,7 +43,6 @@ 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
@@ -77,7 +74,7 @@ import kotlinx.coroutines.withTimeoutOrNull
private val richDraftIds = DraftIdAllocator()
/**
* Runs a long-polling showcase of Telegram's rich-message APIs.
* Runs a long-polling showcase of the rich-message APIs introduced in Telegram Bot API 10.1 through 10.3.
*
* Outgoing [dev.inmo.tgbotapi.types.rich.InputRichMessage] values use one of three representations:
* [InputRichMessageHTML], [InputRichMessageMarkdown], or a typed [InputRichMessageBlocks] tree of
@@ -87,8 +84,7 @@ private val richDraftIds = DraftIdAllocator()
* `tg://photo?id=...` and as typed blocks; [dev.inmo.tgbotapi.requests.send.SendRichMessage] also turns
* 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.
* trigger.
*
* Incoming [dev.inmo.tgbotapi.types.message.content.RichMessageContent] and user-selected content covers
* [onRichMessage], [waitRichMessage], [onlyRichMessageContentMessages], photo reuse, and
@@ -928,49 +924,10 @@ suspend fun main(vararg args: String) {
)
}
onDataCallbackQuery("rich_10_3_callback") { query ->
onMessageDataCallbackQuery(Regex("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 ->
@@ -1163,7 +1120,6 @@ suspend fun main(vararg args: String) {
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 -10
View File
@@ -1,18 +1,9 @@
# RightsChangerBot
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.
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.
## 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:
+2 -2
View File
@@ -11,12 +11,12 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "RightsChangerKt"
mainClassName="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:$ktor_version"
implementation 'io.ktor:ktor-client-logging-jvm:3.2.3'
}
@@ -15,14 +15,12 @@ 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
@@ -32,7 +30,6 @@ 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
@@ -227,23 +224,6 @@ 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 }
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "SlotMachineDetectorBotKt"
mainClassName="SlotMachineDetectorBotKt"
dependencies {
+2 -11
View File
@@ -1,7 +1,7 @@
# StarTransactionsBot
A long-polling bot for Telegram Stars invoices, transaction history, paid media,
refund updates, and TON wallet information.
A long-polling Telegram Stars playground for invoices, transaction history, paid
media, pre-checkout approval, and refund updates.
## Commands
@@ -10,9 +10,6 @@ refund updates, and TON wallet information.
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.
@@ -37,12 +34,6 @@ 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
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "StarTransactionsBotKt"
mainClassName="StarTransactionsBotKt"
dependencies {
@@ -4,7 +4,6 @@ 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
@@ -12,7 +11,6 @@ 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
@@ -21,7 +19,6 @@ 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
@@ -36,7 +33,6 @@ 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
@@ -46,8 +42,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 display the current user's TON wallet card, report TON transfers and
* free-message access, or create a one-Star invoice or paid media.
* handlers create a one-Star invoice or paid media and report payment-related
* updates.
*/
suspend fun main(vararg args: String) {
val botToken = args.first()
@@ -83,32 +79,6 @@ 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 {
+1
View File
@@ -30,6 +30,7 @@ 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,7 +15,8 @@ plugins {
kotlin {
jvm()
js {
// js(LEGACY) {
js(IR) {
browser()
binaries.executable()
}
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "StickerInfoBotBotJvmKt"
mainClassName="StickerInfoBotJvmKt"
dependencies {
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "StickerSetHandlerBotKt"
mainClassName="StickerSetHandlerBotKt"
dependencies {
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "SuggestedPostsBotKt"
mainClassName="SuggestedPostsBotKt"
dependencies {
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "TagsBotKt"
mainClassName="TagsBotKt"
dependencies {
+1 -2
View File
@@ -17,8 +17,7 @@ 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. 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;
- private topic created or edited;
- forum topic reopened;
- General topic hidden or unhidden.
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "TopicsHandlingKt"
mainClassName="TopicsHandlingKt"
dependencies {
@@ -19,8 +19,6 @@ 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
@@ -195,9 +193,8 @@ suspend fun main(vararg args: String) {
onForumTopicCreated {
reply(it, "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"))
onPrivateForumTopicCreated {
reply(it, "Private topic has been created")
}
onForumTopicEdited {
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "UserChatSharedKt"
mainClassName="UserChatSharedKt"
dependencies {
+3 -6
View File
@@ -16,10 +16,6 @@ plugins {
id "org.jetbrains.compose" version "$compose_version"
}
composeCompiler {
targetKotlinPlatforms.set([org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType.js])
}
kotlin {
jvm {
binaries {
@@ -28,7 +24,7 @@ kotlin {
}
}
}
js {
js(IR) {
browser()
binaries.executable()
}
@@ -39,13 +35,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
}
}
@@ -55,6 +51,7 @@ 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
}
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ buildscript {
apply plugin: 'kotlin'
apply plugin: 'application'
application.mainClass = "WebHooksKt"
mainClassName="WebHooksKt"
dependencies {
-27
View File
@@ -1,27 +0,0 @@
# 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)
-19
View File
@@ -1,19 +0,0 @@
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"
}
-113
View File
@@ -1,113 +0,0 @@
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()
}
-35
View File
@@ -1,35 +0,0 @@
<!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>
+6 -1
View File
@@ -14,7 +14,6 @@ allprojects {
nativePartTemplate = "${rootProject.projectDir.absolutePath}/native_template.gradle"
}
repositories {
mavenLocal()
mavenCentral()
google()
if (project.hasProperty("GITHUB_USER") && project.hasProperty("GITHUB_TOKEN")) {
@@ -28,5 +27,11 @@ 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
View File
@@ -5,9 +5,9 @@ org.gradle.jvmargs=-Xmx3148m
kotlin.daemon.jvmargs=-Xmx3g -Xms500m
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
kotlin_version=2.3.20
telegram_bot_api_version=37.0.0
micro_utils_version=0.29.1
serialization_version=1.10.0
ktor_version=3.4.1
compose_version=1.10.2
Binary file not shown.
+3 -1
View File
@@ -1,7 +1,9 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.0-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.2-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+5 -8
View File
@@ -1,7 +1,7 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
# Copyright © 2015 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.
@@ -20,7 +20,7 @@
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
# gradlew start up script for POSIX generated by Gradle.
#
# Important for running:
#
@@ -29,7 +29,7 @@
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
# ksh gradlew
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
@@ -57,7 +57,7 @@
# 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
# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/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/.
@@ -114,7 +114,6 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
@@ -172,7 +171,6 @@ fi
# 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" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
@@ -212,8 +210,7 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
Vendored
+52 -34
View File
@@ -19,12 +19,39 @@
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem gradlew startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions
@rem Catch executions from older scripts and ensure they exit cleanly.
@rem This can be removed once we can be reasonably confident that few people
@rem will be migrating directly to this new wrapper.
goto afterSafetyNet
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
goto exitWithErrorLevel
:afterSafetyNet
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@@ -45,13 +72,14 @@ set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
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
1>&2 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.
goto fail
"%COMSPEC%" /c exit 1
goto exitWithErrorLevel
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
@@ -59,36 +87,26 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
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
1>&2 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.
goto fail
"%COMSPEC%" /c exit 1
goto exitWithErrorLevel
: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 %*
@rem Execute gradlew
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel
:end
@rem End local scope for the variables with windows NT shell
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!
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
:omega
@rem This label must not be changed. We rely on old scripts being able to jump to this point.
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%
-2
View File
@@ -87,5 +87,3 @@ include ":EphemeralMessagesBot"
include ":CommunitiesBot"
include ":BotSubscriptionsBot"
include ":WidgetsBot"