### Initialize Bot and Filter Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.utils/README.md Basic setup for creating a RequestsExecutor and a FlowsUpdatesFilter. This is a prerequisite for most examples. ```kotlin val bot: RequestsExecutor = KtorRequestsExecutor( TelegramAPIUrlsKeeper(BOT_TOKEN) ) val filter = FlowsUpdatesFilter(64) ``` -------------------------------- ### Start Getting Updates with Filter Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.api/README.md Begin receiving updates from Telegram using a predefined filter and a CoroutineScope. This method simplifies the process of listening for updates. ```kotlin bot.startGettingOfUpdates( filter, scope = CoroutineScope(Dispatchers.Default) ) ``` -------------------------------- ### Start Webhook Listener Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.utils/README.md Set up a webhook listener on a specified port using a specific engine. All updates will be processed within the provided lambda. ```kotlin startListenWebhooks( 8081, CIO // require to implement this engine dependency ) { // here will be all updates one by one in $it } ``` -------------------------------- ### Create Bot Instance with Token Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.api/README.md Instantiate a Telegram bot using your bot token. This is the basic way to start. ```kotlin val bot = telegramBot("IT IS YOUR TOKEN") ``` -------------------------------- ### Start Getting Updates and Process in Receiver Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.api/README.md An alternative way to start receiving updates where the update processing logic is defined within a receiver lambda. This approach allows for inline configuration of the FlowsUpdatesFilter. ```kotlin val filter = bot.startGettingOfUpdates( scope = CoroutineScope(Dispatchers.Default) ) { // Here as reveiver will be FlowsUpdatesFilter messageFlow.mapNotNull { it.data as? ContentMessage<*> }.onEach { println(it) }.launchIn( CoroutineScope(Dispatchers.Default) ) } ``` -------------------------------- ### Executing a Telegram Bot API Request Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.core/README.md Demonstrates how to execute a request to the Telegram Bot API using the RequestsExecutor. This example shows how to get information about the bot itself. ```kotlin val requestsExecutor: RequestsExecutor = ... requestsExecutor.execute(GetMe()) ``` -------------------------------- ### Basic Bot with Long Polling Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/README.md This snippet shows a basic bot setup using long polling. It prints bot information and replies to the '/start' command. ```kotlin suspend fun main() { val bot = telegramBot(TOKEN) bot.buildBehaviourWithLongPolling { println(getMe()) onCommand("start") { reply(it, "Hi:)") } }.join() } ``` -------------------------------- ### Start Long Polling with CoroutineScope Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.utils/README.md Alternative way to start receiving updates by providing a CoroutineScope and a lambda to process updates. ```kotlin val filter = bot.startGettingFlowsUpdatesByLongPolling( scope = CoroutineScope(Dispatchers.Default) ) { // place code from examples here with replacing of `filter` by `this` } ``` -------------------------------- ### Bot with Flow Updates Filter Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/README.md This example demonstrates using a FlowsUpdatesFilter to process only the latest updates. It's suitable for bots that need to catch up on missed updates upon startup. ```kotlin suspend fun main() { val bot = telegramBot(TOKEN) val flowsUpdatesFilter = FlowsUpdatesFilter() bot.buildBehaviour(flowUpdatesFilter = flowsUpdatesFilter) { println(getMe()) onCommand("start") { reply(it, "Hi:)") } retrieveAccumulatedUpdates(this).join() } } ``` -------------------------------- ### Get Bot Information Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.api/README.md Retrieve information about the bot using the getMe() extension function, which is a more readable alternative to bot.execute(GetMe). ```kotlin bot.getMe() ``` -------------------------------- ### Start Long Polling with Update Handler Lambda Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.utils/README.md Start long polling and directly provide a lambda function to handle incoming updates. It's recommended to pass a CoroutineScope. ```kotlin bot.startGettingOfUpdatesByLongPolling( { println("Received message update: $it") } ) ``` -------------------------------- ### Process Message Flow Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.api/README.md Filter, map, and launch a coroutine to process incoming messages from the messageFlow. This example demonstrates how to handle specific message types and print them. ```kotlin filter.messageFlow.mapNotNull { it.data as? ContentMessage<*> }.onEach { println(it) }.launchIn( CoroutineScope(Dispatchers.Default) ) ``` -------------------------------- ### Start Long Polling with Filter Object Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.utils/README.md Initiate long polling by passing a pre-created FlowsUpdatesFilter object to the extension function. ```kotlin val filter = FlowsUpdatesFilter(64) bot.startGettingOfUpdatesByLongPolling( filter ) ``` -------------------------------- ### Filter Message Updates with Commands Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.utils/README.md Use `onlyBaseMessageUpdates` to get message updates and then `filterExactCommands` to filter for specific commands. ```kotlin val flow: Flow = ...; // here we are getting flow from somewhere, // for example, FlowsUpdatesFilter#messageFlow flow.onlySentMessageUpdates().filterExactCommands(Regex("start")) ``` -------------------------------- ### Filter for Photo Content Messages Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.utils/README.md Use `asContentMessagesFlow` to get content messages and then `onlyPhotoContentMessages` to filter for photo content. The content is printed to the console. ```kotlin filter.messageFlow.asContentMessagesFlow().onlyPhotoContentMessages().onEach { println(it.content) }.launchIn( CoroutineScope(Dispatchers.Default) ) ``` -------------------------------- ### Filter for Supergroup Chat Events Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.utils/README.md Use `asChatEventsFlow` to get chat events and then `onlySupergroupEvents` to filter for supergroup events. The chat event is printed to the console. ```kotlin filter.messageFlow.asChatEventsFlow().onlySupergroupEvents().onEach { println(it.chatEvent) }.launchIn( CoroutineScope(Dispatchers.Default) ) ``` -------------------------------- ### Simplified Bot Initialization with Behaviour Builder Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.behaviour_builder/README.md Initializes a bot using the Behaviour Builder for simplified command handling. Use this when you want a more declarative way to define bot commands. ```kotlin telegramBotWithBehaviour(token) { onCommand("start".regex) { execute(SendTextMessage(it.chat.id, "This bot can ...")) // replaceable with reply(it, "This bot can ...") when you are using `tgbotapi.extensions.api` } } ``` -------------------------------- ### Add Ktor Server and Client Engines (Groovy) Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.core/README.md Include Ktor server and client dependencies for full functionality, including webhooks. Requires specifying the Ktor version. ```groovy dependencies { // ... implementation "io.ktor:ktor-server-cio:$ktor_version" // for implementing of server engine implementation "io.ktor:ktor-client-okhttp:$ktor_version" // for implementing of additional client engine // ... } ``` -------------------------------- ### Waiting for Specific User Input (Photos) Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.behaviour_builder/README.md Demonstrates how to use a waiter to specifically collect a certain number of photos from a user. It includes an initial request, a handler for invalid updates, and an optional lambda for further requirements checks. ```kotlin telegramBotWithBehaviour(TOKEN) { onCommand("start") { message: TextMessage -> val userPhotos = waitPhoto( SendTextMessage(it.chat.id, "Ok, send me some photo, please"), // init request, can be any `Request` object { update: Update -> // That is update which is NOT passed requirements. In current context we expect some photo, but received something else SendTextMessage(it.chat.id, "Excuse me, but I can accept only photos") // it could be null }, 2, // some count of photos includeMediaGroups = true, // if false, messages related to some media group will be skipped and recognized as incorrect ) { message: CommonMessate -> // this method is optional and you can use it in case you want to add some additional requirements checks message.content // return null if message didn't passed requirements } } } ``` -------------------------------- ### Create Bot Instance with Proxy Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.api/README.md Create a Telegram bot instance with a specified SOCKS proxy. This allows for network traffic routing through a proxy server. ```kotlin val bot = telegramBot("IT IS YOUR TOKEN") { proxy = ProxyBuilder.socks("127.0.0.1", 1080) } ``` -------------------------------- ### Add Ktor Client Engine Only (Groovy) Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.core/README.md Include only the Ktor client dependency if webhooks are not used, simplifying the dependencies. Requires specifying the Ktor version. ```groovy dependencies { // ... implementation "io.ktor:ktor-client-okhttp:$ktor_version" // for implementing of additional client engine // ... } ``` -------------------------------- ### Changelog Format Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/agents/HELPERS.md Follow this markdown format for updating the changelog, organizing changes by module. ```markdown ## 34.0.0 // number of version * `Core`: * // list of changes * `Utils`: * // list of changes * `API`: * // list of changes * `BehaviourBuilder`: * // list of changes * `WebApps`: * // list of changes * `BehaviourBuilderWithFSM`: * // list of changes // etc... ``` -------------------------------- ### Complex Bot Behavior with User Interaction Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/README.md This snippet illustrates building a more complex bot behavior that involves waiting for user input, including photos and text, with custom keyboard options. ```kotlin suspend fun main() { val bot = telegramBot(TOKEN) bot.buildBehaviourWithLongPolling { println(getMe()) val nameReplyMarkup = ReplyKeyboardMarkup( matrix { row { +SimpleKeyboardButton("nope") } } ) onCommand("start") { val photo = waitPhoto( SendTextMessage(it.chat.id, "Send me your photo please") ).first() val name = waitText( SendTextMessage( it.chat.id, "Send me your name or choose \"nope\"", replyMarkup = nameReplyMarkup ) ).first().text.takeIf { it != "nope" } sendPhoto( it.chat, photo.mediaCollection, entities = buildEntities { if (name != null) regular(name) // may be collapsed up to name ?.let(::regular) } ) } }.join() } ``` -------------------------------- ### Create KtorRequestsExecutor Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.core/README.md Instantiate the default Ktor-based RequestsExecutor for API calls. Requires a bot token. ```kotlin val requestsExecutor = KtorRequestsExecutor( TelegramAPIUrlsKeeper(TOKEN) ) ``` -------------------------------- ### Global Exception Handling with CoroutineScope (Method 1) Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/readmes/exceptions_handling.md Configure global exception handling by providing a defaultExceptionsHandler when building the bot's behavior using CoroutineScope. ```kotlin val bot = telegramBot("TOKEN") bot.buildBehaviour ( scope = scope, defaultExceptionsHandler = { it.printStackTrace() } ) { // ... } ``` -------------------------------- ### Gradle Dependency Configuration (Groovy) Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.core/README.md Add this line to your build.gradle file's repositories block to enable fetching the library from Maven Central. This is required for Gradle dependency management. ```groovy mavenCentral() ``` -------------------------------- ### Global Exception Handling with CoroutineScope (Method 2) Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/readmes/exceptions_handling.md An alternative way to set up global exception handling by passing the defaultExceptionsHandler directly during the creation of telegramBotWithBehaviour. ```kotlin val bot = telegramBotWithBehaviour ( "TOKEN", scope = scope, defaultExceptionsHandler = { it.printStackTrace() } ) { // ... } ``` -------------------------------- ### Gradle Dependency Configuration (Kotlin DSL) Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.core/README.md Configure your Gradle project to use the TelegramBotAPI Core library. This includes adding the mavenCentral repository and specifying the dependency. Replace `$telegrambotapi_version` with the actual version. ```groovy implementation "dev.inmo:tgbotapi.core:$telegrambotapi_version" ``` -------------------------------- ### Gradle Dependency Configuration Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.utils/README.md Configure your Gradle project to use the tgbotapi.utils library. Ensure mavenCentral() is in your repositories block. ```groovy implementation "dev.inmo:tgbotapi.utils:$telegrambotapi-extensions-utils_version" ``` ```groovy compile "dev.inmo:tgbotapi.utils:$telegrambotapi-extensions-utils_version" ``` -------------------------------- ### Initialize FlowsUpdatesFilter Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.api/README.md Create a FlowsUpdatesFilter with a specified limit for processing updates. This filter helps in separating different types of incoming updates. ```kotlin val filter = FlowsUpdatesFilter(100) ``` -------------------------------- ### Catching Exceptions with Callbacks Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/readmes/exceptions_handling.md A simpler way to handle exceptions using callbacks. The first lambda handles errors, returning a default value, while the second lambda contains the main logic. ```kotlin safely( { // handle error it.printStackTrace() null // return value } ) { // do something } ``` -------------------------------- ### Maven Dependency Configuration Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.utils/README.md Add this dependency to your Maven project to include the tgbotapi.utils library. ```xml dev.inmo tgbotapi.utils ${telegrambotapi-extensions-utils_version} ``` -------------------------------- ### Gradle Dependency Configuration (Old) Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.core/README.md For older Gradle versions, use the `compile` keyword instead of `implementation` to include the TelegramBotAPI Core library in your project dependencies. ```groovy compile "dev.inmo:tgbotapi.core:$telegrambotapi_version" ``` -------------------------------- ### Maven Dependency Configuration Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.core/README.md Add this dependency to your Maven project to include the TelegramBotAPI Core library. Ensure the `telegrambotapi.version` property is set. ```xml dev.inmo tgbotapi.core ${telegrambotapi.version} ``` -------------------------------- ### Define and Use Custom State in FSM Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.behaviour_builder.fsm/README.md Define a custom state by implementing the `State` interface and overriding the `context` property. Use `strictlyOn` to handle logic within a state and `onCommand` to initiate a state chain with `startChain`. ```kotlin data class StateRealization(override val context: ChatId) : State bot.telegramBotWithBehaviourAndFSMAndStartLongPolling(TOKEN) { strictlyOn { // here your logic of state it // you must return from state handler some other state as a result of this one or null if you want to complete the chain } onCommand("start") { startChain(StateRealization(it.chat.id)) // starting of chain with StateRealization state } } ``` -------------------------------- ### Standard Bot Update Handling Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.behaviour_builder/README.md This is the standard way to handle bot updates using TelegramBotAPI's long polling. ```kotlin val bot = telegramBot(TOKEN) bot.startGettingFlowsUpdatesByLongPolling { messagesFlow.subscribeSafelyWithoutExceptions { // ... } // here I already tired to write this example 😫 } ``` -------------------------------- ### Catching Exceptions with Result Objects Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/readmes/exceptions_handling.md Use this syntax when you prefer to work with Result objects. The onSuccess and onFailure blocks handle success and error cases respectively, and getOrThrow retrieves the value or throws an exception. ```kotlin safelyWithResult { // do something }.onSuccess { // will be called if everything is right // handle success }.onFailure { // will be called if something went wrong // handle error it.printStackTrace() }.getOrThrow() // will return value or throw exception ``` -------------------------------- ### Safe Exception Handling with Default Value Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/readmes/exceptions_handling.md This 'Just safely' approach handles exceptions by returning a default value provided in the error callback. If the error callback is skipped, it throws an exception by default. ```kotlin safely( { it.printStackTrace() "error" } ) { error("Hi :)") // emulate exception throwing "ok" } // result will be with type String ``` -------------------------------- ### Add Gradle Dependency for tgbotapi.api Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.api/README.md Add this line to your build.gradle file to include the tgbotapi.api library in your Gradle project. Ensure mavenCentral() is in your repositories block. ```groovy implementation "dev.inmo:tgbotapi.api:$telegrambotapi_extensions_api_version" ``` ```groovy compile "dev.inmo:tgbotapi.api:$telegrambotapi_extensions_api_version" ``` -------------------------------- ### Safe Exception Handling Without Exceptions Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/readmes/exceptions_handling.md This 'Safely without exceptions' method is similar to 'safely' but allows returning a nullable value when an exception occurs, instead of throwing it. ```kotlin safelyWithouExceptions { // do something } // will returns nullable result type ``` -------------------------------- ### Add TelegramBotAPI Dependency Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi/README.md Include the core TelegramBotAPI library in your Gradle project by adding this dependency. Ensure you use the correct version variable. ```groovy dependencies { // ... implementation "dev.inmo:tgbotapi:$tgBotAPIVersion" } ``` -------------------------------- ### Create FlowsUpdatesFilter with Lambda Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.utils/README.md Instantiate a FlowsUpdatesFilter and process text messages within a coroutine scope. The default internal channel size is 64. ```kotlin val internalChannelsSizes = 128 flowsUpdatesFilter(internalChannelsSizes/* default is 64 */) { textMessages().onEach { println("I have received text message: ${it.content}") }.launchIn(someCoroutineScope) /* ... */ } ``` -------------------------------- ### Add Maven Dependency for tgbotapi.api Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.api/README.md Include this dependency in your Maven project to use the tgbotapi.api library. ```xml dev.inmo tgbotapi.api ${telegrambotapi-extensions-api.version} ``` -------------------------------- ### Send Text Message Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.api/README.md Send a text message to a specified chat using the sendTextMessage() extension function. This is a simplified method compared to bot.execute(SendTextMessage). ```kotlin bot.sendTextMessage(chat, text) ``` -------------------------------- ### Handling Text Messages with Filters Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.behaviour_builder/README.md Defines a trigger to handle text messages with optional filters. Use `includeFilterByChatInBehaviourSubContext` to control context filtering and `additionalFilter` for custom message validation before processing. ```kotlin telegramBotWithBehaviour(TOKEN) { onText( includeFilterByChatInBehaviourSubContext = true, // if false - last lambda will receive all messages instead of filtered by chat messages additionalFilter = { message: TextMessage -> // here you may check incoming message for any requirements before it will be passed to the main lambda } ) { message: TextMessage -> // this here is `BehaviourContext` // here put your actions and additional waiters } } ``` -------------------------------- ### Schedule Poll Closure Exactly at a Specific Time Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.utils/README.md Use `closePollExactAt` with a `DateTime` object to set an exact closing time for a poll. ```kotlin closePollExactAt(DateTime.now() + TimeSpan(10000.0)) ``` -------------------------------- ### Schedule Poll Closure Approximately After a Duration Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.utils/README.md Use `closePollAfter` with a duration in seconds to set an approximate closing time for a poll, which is relative to the time of sending. ```kotlin closePollAfter(10) ``` -------------------------------- ### Schedule Poll Closure Exactly After a Duration Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.utils/README.md Use `closePollExactAfter` with a duration in seconds to set an exact closing time for a poll. ```kotlin closePollExactAfter(10) ``` -------------------------------- ### Changelog Entry with Section Prefix Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/agents/HELPERS.md When updating a known Telegram Bot API changelog part, you can add a prefix with its title to the change entry. ```markdown * `Core`: * (`Guest mode`) // change data ``` -------------------------------- ### Decrypt Telegram Passport Data on JVM Source: https://github.com/insanusmokrassar/ktgbotapi/blob/master/tgbotapi.core/README.md Decrypt Telegram Passport data using a private key within a PKCS8 context. This is specific to the JVM platform. ```kotlin passportMessage.passportData.doInDecryptionContextWithPKCS8Key(privateKey) { val passportDataSecureValue = passport ?.data ?: return@doInDecryptionContextWithPKCS8Key val passportData = (passportMessage.passportData.data.firstOrNull { it is CommonPassport } ?: return@doInDecryptionContextWithPKCS8Key) as CommonPassport val decrypted = passportDataSecureValue.decrypt( passportData.data ) ?.decodeToString() ?: return@doInDecryptionContextWithPKCS8Key println(decrypted) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.