### Handle Start Command and Initial State Transition Source: https://github.com/lavafrai/ktgram/blob/master/docs/StateMachine.md This Kotlin code snippet demonstrates how to handle the 'start' command in a Ktgram router. It clears any existing data, sends an initial greeting, and transitions the bot to the 'WaitingName' state. ```kotlin fun Router<*>.start() { command("start") { handle { data.clear() // Clear all data message.answer("Hello! What is your name?") setState(StartStates.WaitingName) // Transition to the next state } } } ``` -------------------------------- ### Initialize and Run an Echo Bot with ktgram Source: https://github.com/lavafrai/ktgram/blob/master/readme.md This snippet demonstrates how to initialize a Bot instance, set up a text message handler using the DSL routing, and start the polling process to receive updates. ```kotlin import ru.lavafrai.ktgram.client.Bot import ru.lavafrai.ktgram.dispatcher.Dispatcher import ru.lavafrai.ktgram.dispatcher.dsl.text fun main() { val bot = Bot("") val dispatcher = bot.dispatcher dispatcher.routing { text { handle { update.message!!.reply("You said: ${message.text}") } } } bot.runPolling() } ``` -------------------------------- ### Initialize and Run a Telegram Bot in Kotlin Source: https://context7.com/lavafrai/ktgram/llms.txt Demonstrates how to create a Bot instance using your Telegram bot token and optionally configure default properties. It also shows how to start polling for updates from Telegram. ```kotlin import ru.lavafrai.ktgram.client.Bot import ru.lavafrai.ktgram.client.DefaultBotProperties import ru.lavafrai.ktgram.types.ParseMode // Basic bot initialization val bot = Bot(System.getenv("TELEGRAM_BOT_TOKEN")) // Bot with custom properties val properties = DefaultBotProperties( parseMode = ParseMode.MARKDOWN_V2 ) val botWithProps = Bot( token = System.getenv("TELEGRAM_BOT_TOKEN"), properties = properties ) // Start polling for updates bot.runPolling() ``` -------------------------------- ### Modular Handler Organization in Ktgram Source: https://context7.com/lavafrai/ktgram/llms.txt Illustrates organizing Telegram bot handlers into separate functions and files for improved code structure and reusability. This example shows how to define and integrate command and callback query handlers. ```kotlin import ru.lavafrai.ktgram.client.Bot import ru.lavafrai.ktgram.dispatcher.* // handlers/StartHandlers.kt fun Router<*>.startHandlers() { command("start") { handle { message.answer("Welcome! Use /help for available commands.") } } command("help") { handle { message.answer(""" Available commands: /start - Start the bot /help - Show this message /menu - Show main menu """.trimIndent()) } } } // handlers/MenuHandlers.kt fun Router<*>.menuHandlers() { command("menu") { handle { val keyboard = inlineKeyboard { row { button("Option 1", "menu.1") button("Option 2", "menu.2") } } message.answer("Main Menu:", replyMarkup = keyboard) } } callbackQuery(startsWith = "menu.") { handle { val option = callbackQuery.data!!.removePrefix("menu.") callbackQuery.answer("Selected option $option") } } } // Main.kt fun main() { val bot = Bot(System.getenv("TELEGRAM_BOT_TOKEN")) bot.dispatcher.routing { startHandlers() menuHandlers() } bot.runPolling() } ``` -------------------------------- ### Handling Various Message Types in Kotlin Telegram Bots Source: https://context7.com/lavafrai/ktgram/llms.txt Provides examples of specific handlers for different message types like text, photo, location, document, voice, and successful payments. This allows for tailored responses based on the content received. ```kotlin import ru.lavafrai.ktgram.dispatcher.* fun Router<*>.addHandlers() { // Text messages text { handle { message.reply("Received text: ${message.text}") } } // Photo messages photo { handle { val photoFileId = update.message!!.photo!!.last().fileId message.reply("Photo received with fileId: $photoFileId") } } // Location messages location { handle { val loc = message.location!! message.reply("Location: ${loc.latitude}, ${loc.longitude}") } } // Document messages document { handle { message.reply("Document received: ${message.document?.fileName}") } } // Voice messages voice { handle { message.reply("Voice message duration: ${message.voice?.duration} seconds") } } // Successful payment messages payment { handle { message.answer("Payment received: ${message.successfulPayment!!.totalAmount} stars") } } } ``` -------------------------------- ### Build Formatted Messages with Markdown V2 DSL in Ktgram Source: https://context7.com/lavafrai/ktgram/llms.txt This code snippet demonstrates how to use the type-safe Markdown V2 DSL provided by Ktgram to build richly formatted messages. It includes examples of bold, italic, underline, strikethrough, spoiler text, nested formatting, links, mentions, inline code, code blocks with language specification, block quotes, expandable quotes, and escaping special characters. ```kotlin import ru.lavafrai.ktgram.utils.markdownDsl.markdown2 import ru.lavafrai.ktgram.types.ParseMode import ru.lavafrai.ktgram.dispatcher.* fun Router<*>.markdownHandlers() { command("styled") { handle { val text = markdown2 { + "Plain text\n" bold { + "Bold text\n" } italic { + "Italic text\n" } underline { + "Underlined text\n" } strikethrough { + "Strikethrough text\n" } spoiler { + "Hidden spoiler text\n" } bold { + "Bold with " italic { + "nested italic " } + "text\n" } url("https://example.com", "Click here") + "\n" mention(123456789, "User Mention") + "\n" monospace("inline code") + "\n" code("fun main() {\n println(\"Hello\")\n}", "kotlin") quote("This is a block quote\nWith multiple lines") expandableQuote("This is an expandable quote\nClick to expand and see more content") + escape("Special chars: _ * [ ] ( ) ~ ` > # + - = | { } . !") } message.reply(text) } } command("html") { handle { message.reply( "Bold and italic with code", parseMode = ParseMode.HTML ) } } } ``` -------------------------------- ### Creating Inline Keyboards and Handling Callbacks in Kotlin Source: https://context7.com/lavafrai/ktgram/llms.txt Shows how to construct interactive inline keyboards using a DSL, including different button types and callback data. It also demonstrates how to handle callback queries, both with exact matches and prefix-based filtering. ```kotlin import ru.lavafrai.ktgram.types.replymarkup.inlineKeyboard.inlineKeyboard import ru.lavafrai.ktgram.dispatcher.* val exampleKeyboard = inlineKeyboard { row { button("Button 1", "callback_data_1") urlButton("Open Google", "https://google.com") } row { button("Button 2", "callback_data_2") button("Button 3", "callback_data_3") } button("Single Row Button", "callback_data_4") } fun Router<*>.keyboardHandlers() { command("menu") { handle { message.reply("Choose an option:", replyMarkup = exampleKeyboard) } } // Handle callback with exact match callbackQuery("callback_data_1") { handle { callbackQuery.answer("You clicked Button 1!") callbackQuery.message?.editText("Button 1 was clicked") } } // Handle callback with prefix match callbackQuery(startsWith = "callback_data_") { handle { callbackQuery.reply("Callback data: ${callbackQuery.data}") callbackQuery.message?.editReplyMarkup(inlineKeyboard {}) } } } ``` -------------------------------- ### Handle File Uploads and Downloads Source: https://context7.com/lavafrai/ktgram/llms.txt Shows how to upload files from resources or URLs, and how to download a file from Telegram as bytes to re-upload it. ```kotlin import ru.lavafrai.ktgram.types.inputfile.InputFile import ru.lavafrai.ktgram.dispatcher.* fun Router<*>.fileHandlers() { command("resource") { handle { val image = InputFile.fromResource("kotlin.png") message.answerPhoto(image) } } command("url") { handle { val image = InputFile.fromURL("https://example.com/image.png") message.answerPhoto(image) } } photo { handle { val photoFileId = update.message!!.photo!!.last().fileId val photoBytes = bot.downloadFileToBytes(photoFileId) val uploadFile = InputFile.fromBytes(photoBytes) message.answerPhoto(uploadFile, caption = "Here's your photo back!") } } } ``` -------------------------------- ### Create Custom Reply Keyboards with DSL Source: https://context7.com/lavafrai/ktgram/llms.txt This Kotlin code demonstrates how to create custom reply keyboards using a Domain Specific Language (DSL). It includes buttons for text replies and special requests like contacts, location, users, and polls. The `replyKeyboard` builder allows defining rows and buttons, while `removeKeyboard` can be used to dismiss the keyboard. ```kotlin import ru.lavafrai.ktgram.types.replymarkup.replyKeyboard.replyKeyboard import ru.lavafrai.ktgram.types.replymarkup.removeKeyboard import ru.lavafrai.ktgram.dispatcher.* fun Router<*>.replyKeyboardHandlers() { command("keyboard") { handle { val keyboard = replyKeyboard { row { button("Reply Button") requestUsers("Select Users", requestId = 0) } row { requestChat("Select Chat", requestId = 1, chatIsChannel = true) requestContact("Share Contact") } row { requestLocation("Share Location") requestPoll("Create Poll", PollType.REGULAR) } } message.answer("Here's a reply keyboard:", replyMarkup = keyboard) } } command("remove") { handle { message.answer("Keyboard removed", replyMarkup = removeKeyboard()) } } } ``` -------------------------------- ### Telegram Bot Routing and Message Handling DSL in Kotlin Source: https://context7.com/lavafrai/ktgram/llms.txt Illustrates how to set up a dispatcher and use the routing DSL to handle different types of incoming messages, such as text, commands, and photos. This enables modular and organized bot logic. ```kotlin import ru.lavafrai.ktgram.client.Bot import ru.lavafrai.ktgram.dispatcher.* fun main() { val bot = Bot(System.getenv("TELEGRAM_BOT_TOKEN")) val dispatcher = bot.dispatcher dispatcher.routing { // Handle text messages text { handle { message.reply("You said: ${message.text}") } } // Handle commands command("start") { handle { message.answer("Welcome to the bot!") } } // Handle photos photo { handle { message.reply("Nice photo!") } } } bot.runPolling() ``` -------------------------------- ### Display Chat Actions Source: https://context7.com/lavafrai/ktgram/llms.txt Demonstrates the use of the 'using' function to display typing or uploading indicators while performing long-running tasks. ```kotlin import ru.lavafrai.ktgram.types.ChatAction import ru.lavafrai.ktgram.utils.using import kotlinx.coroutines.delay import ru.lavafrai.ktgram.dispatcher.* fun Router<*>.chatActionHandlers() { command("slow") { handle { using(ChatAction.TYPING) { delay(3000) message.reply("Done processing!") } } } command("upload") { handle { using(ChatAction.UPLOAD_PHOTO) { delay(2000) val photo = InputFile.fromURL("https://example.com/large-image.png") message.answerPhoto(photo) } } } } ``` -------------------------------- ### Handle Inline Queries with Ktgram Source: https://context7.com/lavafrai/ktgram/llms.txt Demonstrates how to handle inline queries in Ktgram, allowing users to search for and send content directly from the chat input. It shows how to create an inline query answer with various content types like locations and photos, including an invoice message content. ```kotlin import ru.lavafrai.ktgram.types.inline.inlineQueryResult.answer import ru.lavafrai.ktgram.types.inline.inputMessageContent.InputInvoiceMessageContent import ru.lavafrai.ktgram.types.payments.simplePrice import ru.lavafrai.ktgram.dispatcher.* fun Router<*>.inlineHandlers() { inlineQuery { handle { val invoice = InputInvoiceMessageContent( title = "Product", description = "Buy this product", payload = "product_payload", currency = "XTR", prices = simplePrice(1, "product"), ) inlineQuery.answer { location(55.7558f, 37.6176f, "Moscow", inputMessageContent = invoice) photo( "https://example.com/photo.jpg", "https://example.com/thumbnail.jpg", inputMessageContent = invoice, id = "photo_1" ) } } } } ``` -------------------------------- ### Send Media Messages with KtGram Source: https://context7.com/lavafrai/ktgram/llms.txt Demonstrates how to send photos, documents, audio, videos, media groups, locations, venues, contacts, polls, and dice using the KtGram Router and InputFile types. ```kotlin import ru.lavafrai.ktgram.types.inputfile.InputFile import ru.lavafrai.ktgram.types.media.inputmedia.InputMediaType import ru.lavafrai.ktgram.types.media.inputmedia.toMedia import ru.lavafrai.ktgram.types.media.DiceEmoji import ru.lavafrai.ktgram.dispatcher.* fun Router<*>.mediaHandlers() { command("photo") { handle { val photo = InputFile.fromURL("https://example.com/image.png") message.answerPhoto(photo, caption = "Here's a photo!") } } command("document") { handle { val doc = InputFile.fromURL("https://example.com/file.pdf") message.answerDocument(doc, caption = "Here's a document") } } command("audio") { handle { val audio = InputFile.fromResource("sample.mp3") message.answerAudio(audio) } } command("video") { handle { val video = InputFile.fromURL("https://example.com/video.mp4") message.answerVideo(video) } } command("mediagroup") { handle { val urls = listOf( "https://example.com/image1.jpg", "https://example.com/image2.jpg", "https://example.com/image3.jpg" ) val media = urls.map { InputFile.fromURL(it).toMedia(InputMediaType.PHOTO) } message.answerMediaGroup(media) } } command("location") { handle { message.answerLocation(55.7558f, 37.6176f) } } command("venue") { handle { message.answerVenue(55.754017f, 37.62038f, "Moscow", "Red Square") } } command("contact") { handle { message.answerContact("+1234567890", "John", "Doe") } } command("poll") { handle { message.answerPoll( "What's your favorite language?", listOf("Kotlin", "Java", "Python", "JavaScript") ) } } command("dice") { handle { message.answerDice(DiceEmoji.SLOT_MACHINE) } } } ``` -------------------------------- ### Handle Text Input for User Name and Create Inline Keyboard Source: https://github.com/lavafrai/ktgram/blob/master/docs/StateMachine.md This Kotlin function defines how the bot handles text input when in the 'WaitingName' state. It captures the user's name, stores it, and prompts the user with a question about liking bots, presenting an inline keyboard for the response. ```kotlin fun Router<*>.name() { val likeBotsKeyboard = inlineKeyboard { // Create inline keyboard to send row { button("Yes!", "yes") button("No ", "no") } } text { state(StartStates.WaitingName) { handle { val name = message.text!! data.set("name", name) // Store users name for further use message.answer("Nice to meet you, $name!\nDo you like to write bots?", replyMarkup = likeBotsKeyboard) } } } ``` -------------------------------- ### Using Chat Actions Source: https://github.com/lavafrai/ktgram/blob/master/docs/ChatActionSender.md How to implement automated chat actions such as typing indicators while the bot processes a request. ```APIDOC ## POST /chat/action ### Description Sends a chat action (e.g., typing, uploading photo) to the chat to indicate that the bot is currently processing a request. ### Method POST ### Endpoint /chat/action ### Parameters #### Request Body - **action** (ChatAction enum) - Required - The type of chat action to perform (e.g., TYPING, UPLOAD_PHOTO). - **duration** (Integer) - Optional - The duration in milliseconds to maintain the action. ### Request Example ```kotlin using(ChatAction.TYPING) { delay(5000) message.reply("Processing complete") } ``` ### Response #### Success Response (200) - **status** (string) - Confirmation that the chat action was successfully triggered. #### Response Example { "status": "success" } ``` -------------------------------- ### Error Handling in Ktgram Bots Source: https://context7.com/lavafrai/ktgram/llms.txt Demonstrates how to implement a global error handler in a Ktgram bot to catch and manage exceptions from various handlers. This ensures graceful failure and provides user feedback. ```kotlin import ru.lavafrai.ktgram.dispatcher.* fun main() { val bot = Bot(System.getenv("TELEGRAM_BOT_TOKEN")) bot.dispatcher.routing { command("crash") { handle { throw RuntimeException("Intentional error for testing") } } command("divide") { handle { val num = message.text!!.split(" ").getOrNull(1)?.toIntOrNull() ?: 0 val result = 100 / num message.reply("100 / $num = $result") } } errorHandler { update.chat?.id?.let { bot.sendMessage( it, "An error occurred: ${error.message}\nPlease try again." ) } } } bot.runPolling() } ``` -------------------------------- ### Configure ktgram Dependency in Gradle Source: https://github.com/lavafrai/ktgram/blob/master/readme.md This snippet shows the necessary configuration for build.gradle.kts to include the ktgram library via JitPack repository. ```gradle repositories { maven("https://jitpack.io") } dependencies { implementation("com.github.lavafrai:ktgram:$ktgramVersion") } ``` -------------------------------- ### Handle Text Input for Favorite Programming Language Source: https://github.com/lavafrai/ktgram/blob/master/docs/StateMachine.md This Kotlin function defines the bot's behavior when receiving text input in the 'WaitingLanguage' state. It captures the user's favorite programming language, clears the state, provides a tailored response, and sends a summary of the conversation. ```kotlin fun Router<*>.language() { state(StartStates.WaitingLanguage) { text { handle { val language = message.text!!.lowercase() clearState() if (language == "kotlin") message.answer("Kotlin, you say? That's great choice! Good luck with that!") if (language == "python") message.answer("Oh. That's good choice but did you try Kotlin?") sendSummary( message.chat, data.get("name")!!, true, language ) data.clear() // Clear all data after dialog } } } } ``` -------------------------------- ### Process Payments with Telegram Stars using Ktgram Source: https://context7.com/lavafrai/ktgram/llms.txt This snippet illustrates how to handle payments using Telegram Stars in Ktgram. It covers initiating an invoice, responding to pre-checkout queries, confirming successful payments, and processing refunds for star payments. It includes error handling for invalid payment IDs during refunds. ```kotlin import ru.lavafrai.ktgram.types.payments.simplePrice import ru.lavafrai.ktgram.exceptions.TelegramBadRequest import ru.lavafrai.ktgram.dispatcher.* fun Router<*>.paymentHandlers() { command("buy") { handle { message.answerInvoice( title = "Premium Access", description = "Get premium features for 30 days", payload = "premium_30d", currency = "XTR", prices = simplePrice(100, "Premium Access") ) } } preCheckoutQuery { handle { // Validate the order before accepting payment preCheckoutQuery.answer(true) } } payment { handle { val payment = message.successfulPayment!! message.answer( "Payment successful! You paid ${payment.totalAmount} stars.\n" + "Payment ID: ${payment.telegramPaymentChargeId}" ) } } command("refund") { handle { val paymentId = message.text!!.split(" ").getOrNull(1) if (paymentId == null) { message.answer("Usage: /refund ") return@handle } try { bot.api.refundStarsPayment(message.from!!.id, paymentId) message.answer("Refund processed successfully.") } catch (e: TelegramBadRequest) { message.answer("Refund failed: Invalid payment ID") } } } } ``` -------------------------------- ### Handle Callback Query for 'Like Bots' Decision Source: https://github.com/lavafrai/ktgram/blob/master/docs/StateMachine.md This Kotlin code manages the bot's response to callback queries when in the 'WaitingLikeBots' state. It handles 'yes' and 'no' button presses, responding accordingly and transitioning to the 'WaitingLanguage' state or ending the conversation. ```kotlin fun Router<*>.likeBots() { state(StartStates.WaitingLikeBots) { callbackQuery("yes") { handle { query.message!!.answer("Awesome! I like to develop bots to!\nSo, what's your favorite programming language for that?") setState(StartStates.WaitingLanguage) query.answer() // Do not forget to answer on callback query } } callbackQuery("no") { handle { query.message!!.answer("Not bad not terrible.\nSee you soon.") clearState() sendSummary( update.chat!!, data.get("name")!!, false, null, ) query.answer() } } } ``` -------------------------------- ### POST /chat/action Source: https://context7.com/lavafrai/ktgram/llms.txt Endpoints for displaying chat actions like typing or uploading to the user. ```APIDOC ## POST /chat/action ### Description Displays a specific chat action (e.g., typing, uploading) while the bot processes a request. ### Method POST ### Endpoint /chat/action ### Parameters #### Request Body - **action** (ChatAction) - Required - The action to display (e.g., TYPING, UPLOAD_PHOTO). ### Request Example { "action": "TYPING" } ### Response #### Success Response (200) - **status** (String) - Confirmation of action status. ``` -------------------------------- ### Implement Multi-Step Conversations with State Machine Source: https://context7.com/lavafrai/ktgram/llms.txt This Kotlin code implements a state machine for managing multi-step conversations. It defines states for different stages of a form (waiting for name, age, and confirmation) and uses `setState` and `clearState` to transition between them. Data from the conversation is stored using `data.set` and retrieved with `data.get`. It also utilizes inline keyboards for user interaction within states. ```kotlin import ru.lavafrai.ktgram.stateMachine.State import ru.lavafrai.ktgram.dispatcher.* import ru.lavafrai.ktgram.types.replymarkup.inlineKeyboard.inlineKeyboard // Define states sealed class FormStates { object WaitingName: State() object WaitingAge: State() object WaitingConfirm: State() } fun Router<*>.formHandlers() { command("form") { handle { data.clear() message.answer("Let's fill out a form. What's your name?") setState(FormStates.WaitingName) } } state(FormStates.WaitingName) { text { handle { data.set("name", message.text!!) message.answer("Nice, ${message.text}! How old are you?") setState(FormStates.WaitingAge) } } } state(FormStates.WaitingAge) { text { handle { data.set("age", message.text!!) val confirmKeyboard = inlineKeyboard { row { button("Confirm", "confirm") button("Cancel", "cancel") } } message.answer( "Name: ${data.get("name")}\nAge: ${message.text}\n\nIs this correct?", replyMarkup = confirmKeyboard ) setState(FormStates.WaitingConfirm) } } } state(FormStates.WaitingConfirm) { callbackQuery("confirm") { handle { query.message!!.answer("Form submitted! Thank you, ${data.get("name")}!") clearState() data.clear() query.answer() } } callbackQuery("cancel") { handle { query.message!!.answer("Form cancelled.") clearState() data.clear() query.answer() } } } } ``` -------------------------------- ### Inline Queries API Source: https://context7.com/lavafrai/ktgram/llms.txt Handles inline queries, allowing users to search and send content directly from the chat input. This section covers setting up handlers for inline query events and responding with various content types. ```APIDOC ## Inline Queries ### Description Handle inline queries allowing users to search and send content directly from the chat input. ### Method N/A (Event-driven) ### Endpoint N/A (Client-initiated) ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200) - **answer** (Function) - Function to send results back to the user. - **location** (Function) - Sends a location result. - **photo** (Function) - Sends a photo result. #### Response Example ```kotlin inlineQuery.answer { location(55.7558f, 37.6176f, "Moscow", inputMessageContent = invoice) photo( "https://example.com/photo.jpg", "https://example.com/thumbnail.jpg", inputMessageContent = invoice, id = "photo_1" ) } ``` ``` -------------------------------- ### Send Typing Chat Action in Kotlin Source: https://github.com/lavafrai/ktgram/blob/master/docs/ChatActionSender.md This snippet demonstrates how to send a 'typing' chat action for a specified duration before replying to a user's message. It utilizes the `using` function with `ChatAction.TYPING` and includes a delay. The `ChatAction` enum provides various other actions that can be used. ```kotlin fun Router<*>.handlers() { text { handle { using(ChatAction.TYPING) { delay(5000) message.reply("You said: ${update.message!!.text}") } } } } ``` -------------------------------- ### Declare Bot States in Kotlin Source: https://github.com/lavafrai/ktgram/blob/master/docs/StateMachine.md Defines the states for a bot's conversation flow using a sealed class in Kotlin. Each object within the sealed class represents a distinct state the bot can be in, such as waiting for user input or a specific response. ```kotlin sealed class StartStates { object WaitingName: State() object WaitingLikeBots: State() object WaitingLanguage: State() } ``` -------------------------------- ### POST /media/send Source: https://context7.com/lavafrai/ktgram/llms.txt Endpoints for sending various media types including photos, videos, audio, documents, and media groups. ```APIDOC ## POST /media/send ### Description Sends media content to a chat using InputFile objects. ### Method POST ### Endpoint /media/send ### Parameters #### Request Body - **file** (InputFile) - Required - The media file to send (from URL, resource, or bytes). - **caption** (String) - Optional - Caption for the media. ### Request Example { "file": "InputFile.fromURL(\"https://example.com/image.png\")", "caption": "Here is a photo" } ### Response #### Success Response (200) - **message_id** (Integer) - The ID of the sent message. ``` -------------------------------- ### Payments with Telegram Stars API Source: https://context7.com/lavafrai/ktgram/llms.txt Handles payments using Telegram Stars currency. This includes setting up commands to initiate payments, responding to pre-checkout queries, processing successful payments, and handling refunds. ```APIDOC ## Payments with Telegram Stars ### Description Handle payments using Telegram Stars currency including invoices, pre-checkout queries, and refunds. ### Method N/A (Event-driven and Command-based) ### Endpoint N/A ### Parameters N/A ### Request Example ```kotlin // To initiate a payment message.answerInvoice( title = "Premium Access", description = "Get premium features for 30 days", payload = "premium_30d", currency = "XTR", prices = simplePrice(100, "Premium Access") ) // To handle a refund bot.api.refundStarsPayment(userId, paymentId) ``` ### Response #### Success Response (200) - **answerInvoice** (Function) - Sends an invoice to the user. - **preCheckoutQuery.answer(true)** (Function) - Accepts the pre-checkout query. - **message.answer** (Function) - Confirms successful payment or reports refund status. #### Response Example ```kotlin // After successful payment message.answer("Payment successful! You paid ${payment.totalAmount} stars.\nPayment ID: ${payment.telegramPaymentChargeId}") // After refund attempt message.answer("Refund processed successfully.") ``` ``` -------------------------------- ### Send Conversation Summary in Kotlin Source: https://github.com/lavafrai/ktgram/blob/master/docs/StateMachine.md A suspend function in Kotlin that constructs and sends a summary of the user's interaction. It takes chat, name, a boolean indicating if they like bots, and their preferred language as input, formatting this information into a readable message. ```kotlin suspend fun sendSummary(chat: Chat, name: String, likeBots: Boolean, language: String?) { val summary = buildString { append("Summary:\n") append("Name: $name\n") append("Like bots: ${if (likeBots) "Yes" else "No"}\n") append("Language: ${language ?: "Not specified"}") } chat.sendText(summary) } ``` -------------------------------- ### POST /files/transfer Source: https://context7.com/lavafrai/ktgram/llms.txt Endpoints for downloading files from Telegram and uploading them from various sources. ```APIDOC ## POST /files/transfer ### Description Handles file downloading from Telegram servers and uploading files from local resources or URLs. ### Method POST ### Endpoint /files/transfer ### Parameters #### Request Body - **source** (String) - Required - The source type (URL, resource path, or file_id). ### Request Example { "source": "file_id_from_telegram" } ### Response #### Success Response (200) - **file_bytes** (ByteArray) - The downloaded file content. ``` -------------------------------- ### Markdown V2 DSL API Source: https://context7.com/lavafrai/ktgram/llms.txt Builds formatted messages using a type-safe Markdown V2 DSL. Supports all Telegram formatting options including bold, italic, underline, strikethrough, spoiler, links, mentions, code blocks, and quotes. ```APIDOC ## Markdown V2 DSL ### Description Build formatted messages using a type-safe Markdown V2 DSL with support for all Telegram formatting options. ### Method N/A (DSL usage within message handling) ### Endpoint N/A ### Parameters N/A ### Request Example ```kotlin val text = markdown2 { + "Plain text\n" bold { + "Bold text\n" } italic { + "Italic text\n" } underline { + "Underlined text\n" } strikethrough { + "Strikethrough text\n" } spoiler { + "Hidden spoiler text\n" } bold { + "Bold with " italic { + "nested italic " } + " text\n" } url("https://example.com", "Click here") + "\n" mention(123456789, "User Mention") + "\n" monospace("inline code") + "\n" code("fun main() {\n println(\"Hello\")\n}", "kotlin") quote("This is a block quote\nWith multiple lines") expandableQuote("This is an expandable quote\nClick to expand and see more content") + escape("Special chars: _ * [ ] ( ) ~ ` > # + - = | { } . !") } message.reply(text) ``` ### Response #### Success Response (200) - **reply** (Function) - Sends the formatted message to the chat. #### Response Example ``` Plain text **Bold text** *Italic text* Underlined text ~Strikethrough text~ Hidden spoiler text **Bold with *nested italic* text** [Click here](https://example.com) [User Mention](tg://user?id=123456789) `inline code` ```kotlin fun main() { println("Hello") } ``` > This is a block quote > With multiple lines This is an expandable quote Click to expand and see more content Special chars: _ * [ ] ( ) ~ ` > # + - = | { } . ! ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.