From 89c68ad61873f7bcd6d1f2a073961145e8d4bee3 Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Wed, 29 May 2024 10:32:24 +0000 Subject: [PATCH] deploy: 0931cbd97dcee5e9f46edea20cfcef99f600f17f --- search/search_index.json | 2 +- sitemap.xml | 92 ++++++++++----------- sitemap.xml.gz | Bin 664 -> 664 bytes tgbotapi/logic/behaviour-builder.html | 113 ++++++++++++++++++++++++++ 4 files changed, 160 insertions(+), 47 deletions(-) diff --git a/search/search_index.json b/search/search_index.json index 4da7811..e15962e 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"index.html","title":"Insanus Mokrassar libraries home","text":"

Hello :) It is my libraries docs place and I glad to welcome you here. I hope, this documentation place will help you.

"},{"location":"index.html#projects","title":"Projects","text":"Common and independent TelegramBotAPI Plagubot"},{"location":"index.html#dependencies-graph","title":"Dependencies graph:","text":"%%{init: {\"flowchart\": {\"defaultRenderer\": \"elk\"}} }%% flowchart TB KSLog[KSLog] MicroUtils[MicroUtils] TelegramBotAPI[TelegramBotAPI] TelegramBotAPI-examples[TelegramBotAPI-examples ] PlaguBot[PlaguBot] TelegramBotAPILibraries[TelegramBotAPILibraries] PlaguBotPlugins[PlaguBotPlugins] PlaguBotExample[PlaguBotExample] BooruGrabberTelegramBot[BooruGrabberTelegramBot] SauceNaoTelegramBot[SauceNaoTelegramBot] PlaguPoster[PlaguPoster] PlaguBotSuggestionsBot[PlaguBotSuggestionsBot] TelegramBotTutorial[TelegramBotTutorial] Krontab[Krontab] KJSUiKit[KJSUiKit] SauceNaoAPI[SauceNaoAPI] Navigation[Navigation] TelegramBotAPI-bot_template[TelegramBotAPI-bot_template] PlaguBotPluginTemplate[PlaguBotPluginTemplate] PlaguBotBotTemplate[PlaguBotBotTemplate] MicroUtils --> KSLog TelegramBotAPI --> MicroUtils TelegramBotAPI-examples --> TelegramBotAPI PlaguBot --> TelegramBotAPI TelegramBotAPILibraries --> PlaguBot PlaguBotPlugins --> TelegramBotAPILibraries PlaguBotExample --> PlaguBotPlugins BooruGrabberTelegramBot --> TelegramBotAPI BooruGrabberTelegramBot --> Krontab SauceNaoTelegramBot --> TelegramBotAPI SauceNaoTelegramBot --> SauceNaoAPI TelegramBotTutorial --> PlaguBotPlugins PlaguBotSuggestionsBot --> PlaguBotPlugins PlaguPoster --> PlaguBotPlugins PlaguPoster --> Krontab SauceNaoAPI --> MicroUtils Navigation --> MicroUtils TelegramBotAPI-bot_template -.- TelegramBotAPI PlaguBotPluginTemplate -.- PlaguBot PlaguBotBotTemplate -.- PlaguBot"},{"location":"krontab/index.html","title":"krontab","text":"

Library was created to give opportunity to launch some things from time to time according to some schedule in runtime of applications.

"},{"location":"krontab/index.html#how-to-use","title":"How to use","text":"

Here you may find the builder for Krontab templates creation.

There are several ways to configure and use this library:

Anyway, to start some action from time to time you will need to use one of extensions/functions:

val kronScheduler = /* creating of KronScheduler instance */;\n\nkronScheduler.doWhile {\n    // some action\n    true // true - repeat on next time\n}\n
"},{"location":"krontab/index.html#including-in-project","title":"Including in project","text":"

If you want to include krontab in your project, just add next line to your dependencies part:

implementation \"dev.inmo:krontab:$krontab_version\"\n

Next version is the latest currently for the library:

For old version of Gradle, instead of implementation word developers must use compile.

"},{"location":"krontab/index.html#config-from-string","title":"Config from string","text":"

Developers can use more simple way to configure repeat times is string. String configuring like a crontab, but with a little bit different meanings:

/--------------- Seconds\n| /------------- Minutes\n| | /----------- Hours\n| | | /--------- Days of months\n| | | | /------- Months\n| | | | | /----- (optional) Year\n| | | | | | /--- (optional) Timezone offset\n| | | | | | |  / (optional) Week days\n* * * * * * 0o *w\n

It is different with original crontab syntax for the reason, that expected that in practice developers will use seconds and minutes with more probability than months (for example) or even years. In fact, developers will use something like:

doWhile(\"/5 * * * *\") {\n    println(\"Called\")\n    true // true - repeat on next time\n}\n

Another version:

doInfinity(\"/5 * * * *\") {\n    println(\"Called\")\n}\n

Both of examples will print Called message every five seconds.

"},{"location":"krontab/index.html#config-via-builder","title":"Config via builder","text":"

Also, this library currently supports DSL for creating the same goals:

val kronScheduler = buildSchedule {\n    seconds {\n        from (0) every 5\n    }\n}\nkronScheduler.doWhile {\n    println(\"Called\")\n    true // true - repeat on next time\n}\n

Or

val kronScheduler = buildSchedule {\n    seconds {\n        0 every 5\n    }\n}\nkronScheduler.doWhile {\n    println(\"Called\")\n    true // true - repeat on next time\n}\n

Or

val kronScheduler = buildSchedule {\n    seconds {\n        0 every 5\n    }\n}\nkronScheduler.doInfinity {\n    println(\"Called\")\n}\n

All of these examples will do the same things: print Called message every five seconds.

"},{"location":"krontab/index.html#do-functions","title":"do* functions","text":"

With regular doOnce/doWhile/doInfinity there are two types of their variations: local and timezoned. Local variations (doOnceLocal/doWhileLocal/doInfinityLocal) will pass DateTime as an argument into the block:

doInfinityLocal(\"/5 * * * *\") {\n    println(it) // will print current date time\n}\n

Timezoned variations (doOnceTz/doWhileTz/doInfinityTz) will do the same thing but pass as an argument DateTimeTz:

doInfinityTz(\"/5 * * * * 0o\") {\n    println(it) // will print current date time in UTC\n}\n

It is useful in cases when you need to get the time of calling and avoid extra calls to system time.

"},{"location":"krontab/index.html#helpful-table-for","title":"Helpful table for","text":"No args Local DateTime Local DateTimeTz with offset of KronScheduler Call only near time doOnce doOnceLocal doOnceTz Call while condition is true doWhile doWhileLocal doWhileTz Work infinity* doInfinity doInfinityLocal doInfinityTz

*Here there is an important notice, that Work infinity is not exactly infinity. Actually, that means that do while coroutine is alive and in fact executing will be stopped when coroutine became cancelled.

"},{"location":"krontab/index.html#kronscheduler-as-a-flow","title":"KronScheduler as a Flow","text":"

Any KronScheduler can be converted to a Flow<DateTime> using extension asFlow:

val kronScheduler = buildSchedule {\n    seconds {\n        0 every 1\n    }\n}\n\nval flow = kronScheduler.asFlow()\n

So, in this case any operations related to flow are available, and it is expected that they will work correctly. For example, it is possible to use this flow with takeWhile:

flow.takeWhile {\n    condition()\n}.collect {\n    action()\n}\n
"},{"location":"krontab/index.html#offsets","title":"Offsets","text":"

Offsets in this library works via passing parameter ending with o in any place after month config. Currently, there is only one format supported for offsets: minutes of offsets. To use time zones you will need to call next method with DateTimeTz argument or nextTimeZoned method with any KronScheduler instance, but in case if this scheduler is not instance of KronSchedulerTz it will work like you passed just DateTime.

Besides, in case you wish to use time zones explicitly, you will need to get KronSchedulerTz. It is possible by:

"},{"location":"krontab/index.html#note-about-week-days","title":"Note about week days","text":"

Unlike original CRON, here week days:

"},{"location":"krontab/describing/krontabscheduler.html","title":"KrontabScheduler","text":"

KronScheduler is the simple interface with only one function next. This function optionally get as a parameter DateTime which will be used as start point for the calculation of next trigger time. This function will return the next DateTime when something must happen.

"},{"location":"krontab/describing/krontabscheduler.html#default-realisation","title":"Default realisation","text":"

Default realisation (CronDateTimeScheduler) can be created using several ways:

In the examples below the result of created scheduler will be the same.

"},{"location":"krontab/describing/krontabscheduler.html#crontab-like-way","title":"Crontab-like way","text":"

Crontab-like syntax

See String format for more info about the crontab-line syntax

This way will be very useful for cases when you need to configure something via external configuration (from file on startup or via some parameter from requests, for example):

val schedule = \"5 * * * *\"\nval scheduler = buildSchedule(schedule)\n\nscheduler.asFlow().onEach {\n  // this block will be called every minute at 5 seconds\n}.launchIn(someCoroutineScope)\n
"},{"location":"krontab/describing/krontabscheduler.html#lambda-way","title":"Lambda way","text":"

In case of usage builder (lets call it lambda way), you will be able to configure scheduler in more type-safe way:

val scheduler = buildSchedule {\n  seconds {\n    at(5)\n  }\n}\n\nscheduler.asFlow().onEach {\n  // this block will be called every minute at 5 seconds\n}.launchIn(someCoroutineScope)\n
"},{"location":"krontab/describing/krontabscheduler.html#custom-scheduler","title":"Custom scheduler","text":"

You are always able to use your own realisation of scheduler. For example:

class RandomScheduler : KronScheduler {\n  override suspend fun next(relatively: DateTime): DateTime {\n    return relatively + DateTimeSpan(seconds = Random.nextInt() % 60)\n  }\n}\n

In the example above we have created RandomScheduler, which will return random next time in range 0-60 seconds since relatively argument.

"},{"location":"krontab/describing/string-format.html","title":"String format","text":"

As in crontab util, this library have almost the same format of string:

Seconds Minutes Hours Days of months Months Years Timezone Offset Week days Milliseconds Range 0..59 0..59 0..23 0..30 0..11 Any Int Any Int 0..6 0..999 Suffix - - - - - - o w ms Optional \u274c \u274c \u274c \u274c \u274c \u2705 \u2705 \u2705 \u2705 Full syntax support \u2705 \u2705 \u2705 \u2705 \u2705 \u2705 \u274c \u2705 \u2705 Position 0 1 2 3 4 Any after months Any after months Any after months Any after months Examples 0, */15, 30 0, */15, 30 0, */15, 22 0, */15, 30 0, */5, 11 0, */15, 30 60o (UTC+1) 0w, */2w, 4w 0ms, */150ms, 300ms

Example with almost same description:

/-------------------- (0-59) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Seconds\n| /------------------ (0-59) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Minutes\n| | /---------------- (0-23) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Hours\n| | | /-------------- (0-30) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Days of months\n| | | | /------------ (0-11) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Months\n| | | | | /---------- (optional, any int) Year\n| | | | | | /-------- (optional) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Timezone offset\n| | | | | | |  /----- (optional, 0-6) \u00b7\u00b7\u00b7 Week days\n| | | | | | |  |  /-- (optional, 0-999) \u00b7 Milliseconds (0 by default)\n* * * * * * 0o *w 0ms\n

Years, timezone, week days and milliseconds are optional settings. Next snippets are equal:

*/15 * * * *\n*/15 * * * * * // with year\n*/15 * * * * * 0ms // with year and milliseconds\n
"},{"location":"krontab/describing/string-format.html#supported-syntax","title":"Supported syntax","text":"

Currently the library support next syntax for date/time elements:

"},{"location":"krontab/describing/string-format.html#ranges","title":"Ranges","text":"

Ranges are working like common rangeTo (or ..) in kotlin:

0-5 * * * *\n

In the example above scheduler will trigger every second from the beginning of the minute up to fifth second of minute.

"},{"location":"krontab/describing/string-format.html#startstep","title":"Start/Step","text":"

Start/step is a little bit more complicated syntax. It means start from the first element, repeat triggering every second element. Examples:

5/15 * * * *\n

Means that each minute starting from fifth second it will repeat triggering every fifteenth second: 5, 20, 35, 50.

"},{"location":"krontab/describing/string-format.html#every","title":"Every","text":"

Every is more simple syntax and could be explained as a shortcut for 0/{int}. Example:

*/15 * * * *\n

Means that each minute it will repeat triggering every fifteenth second: 0, 15, 30, 45.

"},{"location":"krontab/describing/string-format.html#just-at-the-time","title":"Just at the time","text":"

The most simple syntax. It means, that scheduler will call triggering every time when element was reached:

15 * * * *\n

Means that each minute scheduler will call triggering at the fifteenth second.

"},{"location":"krontab/describing/string-format.html#listing","title":"Listing","text":"

All the previous elements can be combined with listing. Lets just see several examples:

0,10 * * * *\n

Will trigger every minute at the 0 and 10 seconds (see Just at the time)

0-5,10 * * * *\n

Will trigger every minute from 0 to 5 seconds and at the 10 seconds (see Ranges)

"},{"location":"krontab/describing/string-format.html#examples","title":"Examples","text":""},{"location":"krontab/introduction/faq.html","title":"FAQ","text":""},{"location":"krontab/introduction/faq.html#how-oftern-new-versions-are-releasing","title":"How oftern new versions are releasing?","text":"

Not very often. It depends on libraries (coroutines, korlibs/klock) updates and on some new awesome, but lightweight, features coming.

"},{"location":"krontab/introduction/faq.html#where-this-library-could-be-useful","title":"Where this library could be useful?","text":"

First of all, this library will be useful for long uptime applications which have some tasks to do from time to time.

"},{"location":"krontab/introduction/faq.html#how-to-use-crontab-like-syntax","title":"How to use crontab-like syntax?","text":"

In two words, you should call buildSchedule or createSimpleScheduler:

buildSchedule(\"5 * * * *\").asFlow().collect { /* do something */ }\n

You can read more about syntax in String format section.

"},{"location":"krontab/introduction/how-to-use.html","title":"How to use","text":""},{"location":"krontab/introduction/how-to-use.html#previous-pages","title":"Previous pages","text":""},{"location":"krontab/introduction/how-to-use.html#buildschedule","title":"buildSchedule","text":"

Custom KronScheduler

You are always may create your own scheduler. In this section will be presented different ways and examples around standard CronDateTimeScheduler builders buildSchedule. You can read about schedulers in KrontabScheduler

Currently, buildSchedule is the recommended start point for every scheduler. Usually, it is look like:

val scheduler = buildSchedule(\"5 * * * *\")\n

Or:

val scheduler = buildSchedule {\n  seconds {\n    at(5)\n  }\n}\n

On the top of any KronScheduler currently there are several groups of extensions:

"},{"location":"krontab/introduction/how-to-use.html#executes","title":"Executes","text":"

All executes are look like do.... All executes are described below:

"},{"location":"krontab/introduction/how-to-use.html#shortcuts","title":"Shortcuts","text":"

Shortcuts are the constants that are initializing in a lazy way to provide preset KronSchedulers. For more info about KrontabScheduler you can read its own page.

"},{"location":"krontab/introduction/how-to-use.html#flows","title":"Flows","text":"

Here currently there is only one extension for KronScheduler: KronScheduler#asFlow. As a result you will get Flow<DateTime> (in fact SchedulerFlow) which will trigger next emit on each not null next DateTime

"},{"location":"krontab/introduction/including-in-project.html","title":"Including in project","text":"

In two words, you must add dependency dev.inmo:krontab:$krontab_version to your project. The latest version presented by next badge:

"},{"location":"krontab/introduction/including-in-project.html#notice-about-repository","title":"Notice about repository","text":"

To use this library, you will need to include MavenCentral repository in you project

"},{"location":"krontab/introduction/including-in-project.html#buildgradle","title":"build.gradle","text":"
mavenCentral()\n
"},{"location":"krontab/introduction/including-in-project.html#dependencies","title":"Dependencies","text":"

Next snippets must be placed into your dependencies part of build.gradle (for gradle) or pom.xml (for maven).

"},{"location":"krontab/introduction/including-in-project.html#gradle","title":"Gradle","text":"
implementation \"dev.inmo:krontab:$krontab_version\"\n
"},{"location":"krontab/introduction/including-in-project.html#maven","title":"Maven","text":"
<dependency>\n    <groupId>dev.inmo</groupId>\n    <artifactId>krontab</artifactId>\n    <version>${krontab_version}</version>\n</dependency>\n
"},{"location":"kslog/index.html","title":"KSLog","text":"

It is simple and easy-to-use tool for logging on the most popular platforms in Kotlin Multiplatform:

By default, KSLog is using built-in tools for logging on each supported platform:

But you always may create your logger and customize as you wish:

KSLog.default = KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->\n    // do your logging\n}\n

This library also supports native targets in experimental mode. By default, all native targets will use simple printing in the console

"},{"location":"kslog/index.html#how-to-use","title":"How to use","text":""},{"location":"kslog/index.html#fast-travel","title":"Fast-travel","text":"

Just use some boring extensions like:

KSLog.i(\"Some message\")\n// OR\nKSLog.i(\"Some tag\", \"Some message\")\n// OR\nKSLog.i(\"Some tag\", \"Some message\", IllegalArgumentException(\"So, that is exception :)\"))\n// OR\nKSLog.i(\"Some optional tag\", Exception(\"Optional\")) { \"Lazy inited message\" }\n// OR\nKSLog.iS(\"Some optional tag\", Exception(\"Optional\")) { \"Lazy inited message for suspendable calculation of text\" }\n// OR EVEN\nKSLog.l(LogLevel.INFO, \"Some tag\", \"Some message\", IllegalArgumentException(\"So, that is exception :)\"))\n// OR\nKSLog.l(LogLevel.INFO, \"Some optional tag\", IllegalArgumentException(\"So, that is exception :)\")) { \"And lazily inited message\" }\n
"},{"location":"kslog/index.html#a-little-bit-deeper","title":"A little bit deeper","text":"

There are several important \u201cterms\u201d in context of this library:

Every logging extension (like KSLog.i) have its analog with lazy inited message text and the same one with suffix S (like KSLog.iS) for the suspendable message calculation.

Default logger can be created by passing defaultTag and one of variants log level filters: set or minimal loggable level. In JVM you also may setup any logger as base logger for default realizations of KSLog. Besides, you may use your own callback (on any target platform) as output of logging:

val logger = KSLog { logLevel, optionalTag, message, optionalThrowable ->\n    println(\"[$logLevel] $optionalTag - $message: $optionalThrowable.stackTraceToString()\")\n}\n

In the example above we will take the logger which will just print incoming data as common output.

"},{"location":"kslog/index.html#installation","title":"Installation","text":""},{"location":"kslog/index.html#gradle","title":"Gradle","text":"
implementation \"dev.inmo:kslog:$kslog_version\"\n
"},{"location":"kslog/index.html#maven","title":"Maven","text":"
<dependency>\n  <groupId>dev.inmo</groupId>\n  <artifactId>kslog</artifactId>\n  <version>${kslog_version}</version>\n</dependency>\n
"},{"location":"kslog/logging.html","title":"Logging","text":"

Message type notice

On this page all the messages will be just simple String, but you may pass any object as the message

As has been said in the setup section, this library contains next levels of logging with their default representations on each platform:

Weight (by order) LogLevel name JS JVM Loggers Android 0 TRACE console.trace + console.debug Level.FINEST Log.d 1 DEBUG console.debug Level.FINER Log.d 2 VERBOSE console.info Level.FINE Log.v 3 INFO console.info Level.INFO Log.i 4 WARNING console.warn Level.WARNING Log.w 5 ERROR console.error Level.SEVERE Log.e 6 ASSERT console.error Level.SEVERE Log.wtf

Each of these levels have fullname and shortname shortcat extensions:

And any of these shortcuts may accept one of several arguments combinations:

So, when you want to log some expected exception, there are three common ways to do it:

val logger = KSLog.default\n\n// with callback\nlogger.info(tag, throwable) {\n  \"Some your message for this event\"\n}\n\n// with suspendable callback\nlogger.infoS(tag, throwable) {\n  withContext(Dispatchers.Default) {\n    \"Some your message for this event\"\n  }\n}\n\n// Just with message\nlogger.info(\"Some your message for this event\", throwable)\n\n// With message and tag as strings\nlogger.info(tag, \"Some your message for this event\", throwable)\n

Of course, any of this calls can be shortenned:

val logger = KSLog.default\n\n// with callback\nlogger.i(tag, throwable) {\n  \"Some your message for this event\"\n}\n\n// with suspendable callback\nlogger.iS(tag, throwable) {\n  withContext(Dispatchers.Default) {\n    \"Some your message for this event\"\n  }\n}\n\n// Just with message\nlogger.i(\"Some your message for this event\", throwable)\n\n// With message and tag as strings\nlogger.i(tag, \"Some your message for this event\", throwable)\n

There is special shortcat - for base performLog. In that case the only change is that you will require to pass the LogLevel more obviously:

val logger = KSLog.default\n\n// with callback\nlogger.log(LogLevel.INFO, tag, throwable) {\n  \"Some your message for this event\"\n}\n\n// with suspendable callback\nlogger.logS(LogLevel.INFO, tag, throwable) {\n  withContext(Dispatchers.Default) {\n    \"Some your message for this event\"\n  }\n}\n\n// Just with message\nlogger.log(LogLevel.INFO, \"Some your message for this event\", throwable)\n\n// With message and tag as strings\nlogger.log(LogLevel.INFO, tag, \"Some your message for this event\", throwable)\n

OR

val logger = KSLog.default\n\n// with callback\nlogger.l(LogLevel.INFO, tag, throwable) {\n  \"Some your message for this event\"\n}\n\n// with suspendable callback\nlogger.lS(LogLevel.INFO, tag, throwable) {\n  withContext(Dispatchers.Default) {\n    \"Some your message for this event\"\n  }\n}\n\n// Just with message\nlogger.l(LogLevel.INFO, \"Some your message for this event\", throwable)\n\n// With message and tag as strings\nlogger.l(LogLevel.INFO, tag, \"Some your message for this event\", throwable)\n
"},{"location":"kslog/setup.html","title":"Setup","text":""},{"location":"kslog/setup.html#dependency-installation","title":"Dependency installation","text":""},{"location":"kslog/setup.html#gradle-groovy","title":"Gradle (Groovy)","text":"
implementation \"dev.inmo:kslog:$kslog_version\"\n
"},{"location":"kslog/setup.html#gradle-kotlin-script","title":"Gradle (Kotlin Script)","text":"
implementation(\"dev.inmo:kslog:$kslog_version\")\n
"},{"location":"kslog/setup.html#maven-pom","title":"Maven (pom)","text":"
<dependency>\n  <groupId>dev.inmo</groupId>\n  <artifactId>kslog</artifactId>\n  <version>${kslog_version}</version>\n</dependency>\n
"},{"location":"kslog/setup.html#setup-in-code","title":"Setup in code","text":"

The main point in setup in your code is to setup default logger:

KSLog.default = KSLog(\"defaultTag\")\n

You may use custom messageFormatter in any of KSLog factory to customize output of KSLog logging. For example:

KSLog(\n  \"loggingWithCustomFormat\",\n  messageFormatter = { level, tag, message, throwable ->\n    println(\"[$level] $tag - $message: $throwable\")\n  }\n)\n

Additionally you may use one of several different settings:

In case you are passing minLoggingLevel, the level and more important levels will be passed to logs. For example, when you are settings up your logger as in next snippet:

val logger = KSLog(\n    \"exampleTag\",\n    minLoggingLevel = LogLevel.INFO\n)\n

The next levels will be logged with logger:

"},{"location":"kslog/setup.html#special-loggers","title":"Special loggers","text":""},{"location":"kslog/setup.html#callbackkslog","title":"CallbackKSLog","text":"

It is logger which will call incoming performLogCallback on each logging. This logger can be create simply with one callback:

KSLog { level, tag, message, throwable ->\n  println(\"[$level] $tag - $message: $throwable\")\n}\n
"},{"location":"kslog/setup.html#taglogger","title":"TagLogger","text":"

It is simple value class which can be used for zero-cost usage of some tag and calling for KSLog.default. For example, if you will create tag logger with next code:

val logger = TagLogger(\"tagLoggerTag\")\n

The logger will call KSLog.default with the tag tagLoggerTag on each calling of logging.

"},{"location":"kslog/setup.html#filterkslog","title":"FilterKSLog","text":"

This pretty simple logger will call its fallbackLogger only in cases when incoming messageFilter will return true for logging:

val baseLogger = KSLog(\"base\") // log everything with the tag `base` if not set other\nval filtered = baseLogger.filtered { _, t, _ ->\n    t == \"base\"\n}\n

In the example above baseLogger will perform logs in two ways: when it has been called directly or when we call log performing with the tag \"base\" or null. Besides, you can see there extension filtered which allow to create FilterKSLog logger with simple lambda.

"},{"location":"kslog/setup.html#typedkslog","title":"TypedKSLog","text":"

This logger accepts map of types with the target loggers. You may build this logger with the special simple DSL:

val baseLogger = KSLog(\"base\") // log everything with the tag `base` if not set other\nval typed = buildTypedLogger {\n  on<Int>(baseLogger) // log all ints to the baseLogger\n  on<Float> { _, _, message, _ ->// log all floats to the passed logger\n    println(message.toString()) // just print all floats\n  }\n  default { level, tag, message, throwable ->\n    KSLog.performLog(level, tag, message, throwable)\n  }\n}\n
"},{"location":"kslog/setup.html#automatical-loggers","title":"Automatical loggers","text":"

There are two things which can be useful in your code: logger and logTag extensions. logTag is the autocalculated by your object classname tag. logger extension can be used with applying to any object like in the next snippet:

class SomeClass {\n  init {\n    logger.i(\"inited\")\n  }\n}\n

The code above will trigger calling of logging in KSLog.default with level LogLevel.INFO using tag SomeClass and message \"inited\". As you could have guessed, logger is using TagLogger with logTag underhood and the most expensive operation here is automatical calculation of logTag.

"},{"location":"kslog/setup.html#jvm-specific-setup","title":"JVM specific setup","text":"

For JVM you may setup additionally use java loggers as the second parameter of KSLog factory. For example:

KSLog(\n  \"yourTag\"\n  Logger.getLogger(\"YourJavaLoggerName\")\n)\n
"},{"location":"micro_utils/index.html","title":"MicroUtils","text":"

MicroUtils is a set of libraries to help me (and, I hope, you too) in some routine doings of coding.

First of all, this library collection is oriented to use next technologies:

Warning

Due to complexity of this library, it is possible that some things will be missed or inactual. Me and the users of this library will try hard to keep its docs as actual as possible, but in case you will find some inconsistency of docs and library work (signatures, behaviour, API) you may write me directly in my telegram

"},{"location":"micro_utils/colors.ktstemplate.html","title":"Colors.ktstemplate","text":"

group=dev.inmo artifact=micro_utils.colors.common package=$group.$artifact central_package=$group/$artifact

"},{"location":"micro_utils/colors.ktstemplate.html#colors","title":"Colors","text":"

Adding dependency:

implementation \"$group:$artifact:latest\"\n

Info

All the samples below will represent HEXAColor with r==0xaa, g==0xff, b==0x00 and a==0xff

This package contains mainly one file: HEXAColor. This file contains unified color with HEXA format. It consumes UInt by default constructor and r/g/b/a parameters in other main constructors:

HEXAColor(0xaaff00ffu) // 0xRGBAu as UInt\nHEXAColor(r = 0xaa, g = 0xff, b = 0x00, a = 0xff)\nHEXAColor(r = 0xaa, g = 0xff, b = 0x00, aOfOne = 1f)\n

Besides, you may use one of converters:

HEXAColor.fromAhex(0xffaaff00u) // 0xARGBu as UInt\nHEXAColor.parse(\"rgba(aa, ff, 00, ff)\")\nHEXAColor.parse(\"rgba(aa, ff, 00)\")\nHEXAColor.parse(\"#af0\")\nHEXAColor.parse(\"#af0f\")\nHEXAColor.parse(\"#aaff00\")\nHEXAColor.parse(\"#aaff00ff\")\n
"},{"location":"micro_utils/colors.html","title":"Colors","text":"

Adding dependency:

implementation \"dev.inmo:micro_utils.colors.common:latest\"\n

Info

All the samples below will represent HEXAColor with r==0xaa, g==0xff, b==0x00 and a==0xff

This package contains mainly one file: HEXAColor. This file contains unified color with HEXA format. It consumes UInt by default constructor and r/g/b/a parameters in other main constructors:

HEXAColor(0xaaff00ffu) // 0xRGBAu as UInt\nHEXAColor(r = 0xaa, g = 0xff, b = 0x00, a = 0xff)\nHEXAColor(r = 0xaa, g = 0xff, b = 0x00, aOfOne = 1f)\n

Besides, you may use one of converters:

HEXAColor.fromAhex(0xffaaff00u) // 0xARGBu as UInt\nHEXAColor.parse(\"rgba(aa, ff, 00, ff)\")\nHEXAColor.parse(\"rgba(aa, ff, 00)\")\nHEXAColor.parse(\"#af0\")\nHEXAColor.parse(\"#af0f\")\nHEXAColor.parse(\"#aaff00\")\nHEXAColor.parse(\"#aaff00ff\")\n
"},{"location":"micro_utils/resources.html","title":"Resources","text":"

Package: dev.inmo:micro_utils.resources

This package aimed to make some multiplatform support for resources of your application. As for now, there is only support for strings. Sample:

object Translations {\n    val someVariable = buildStringResource(\n        \"Sample default string\"\n    ) {\n        IetfLang.German variant lazy \"Beispiel f\u00fcr eine Standardzeichenkette\"\n    }\n}\n

In this case, you will be able to use it with next logic:

Translation.someVariable.translation(IetfLang.French) // \"Sample default string\" as default one\nTranslation.someVariable.translation(IetfLang.German) // \"Beispiel f\u00fcr eine Standardzeichenkette\" as available variant\nTranslation.someVariable.translation(IetfLang.German.DE) // \"Beispiel f\u00fcr eine Standardzeichenkette\" as available parent variant\n
"},{"location":"micro_utils/resources.html#additional-opportunities-on-android-platform","title":"Additional opportunities on Android platform","text":"

On Android you may use Configuration (as well as Resources or Context) to get translation for current locale. For example:

val context: Context = // context retrieving\n\ncontext.translation(Translation.someVariable)\n
"},{"location":"micro_utils/resources.html#additional-opportunities-on-jvm-platform","title":"Additional opportunities on JVM platform","text":"

On JVM platform you usually may use Locale.getDefault() to get Locale object and pass it to translation extension:

Translation.someVariable.translation(Locale.getDefault())\nTranslation.someVariable.translation() // Locale.getDefault() hidden\n
"},{"location":"micro_utils/startup.html","title":"Startup","text":"

This package contains unified simple Plugin/Launcher tools for separating of your apps parts

"},{"location":"micro_utils/startup.html#plugin","title":"Plugin","text":"

To define plugin, you must use StartPlugin as supertype for your plugin. Restrictions are simple: plugins must be an object or class with empty constructor. Basic sample is here:

object YourPlugin : StartPlugin {\n    // Body of your plugin\n}\n

Each plugin may contains to parts:

object YourPlugin : StartPlugin {\n    override fun Module.setupDI(config: JsonObject) {\n        // here you may setup any DI content you wish to be available in context of current Koin module\n    }\n    override fun startPlugin(koin: Koin) {\n        // all staff from setupDI and the same function of other plugins is available in koin\n    }\n}\n
"},{"location":"micro_utils/startup.html#launcher","title":"Launcher","text":"

Basically, launcher module can be used to start application directly from gradle. Let\u2019s imagine you have this gradle groovy config:

plugins {\n    id 'org.jetbrains.kotlin.jvm'\n    id \"org.jetbrains.kotlin.plugin.serialization\"\n    id 'application'\n}\n\ndependencies {\n    // kotlin and other dependencies\n    implementation (\"dev.inmo:micro_utils.startup.launcher:$latest_version\")\n}\n\napplication {\n    mainClassName = 'dev.inmo.micro_utils.startup.launcher.MainKt'\n}\n

You will be able to run your project with gradle command ./gradlew run --args=\"path/to/config.json\". config.json must contains something like:

{\n    \"plugins\": [\n        \"dev.inmo.micro_utils.startup.launcher.HelloWorldPlugin\"\n    ]\n}\n

In current case you will see in logger different logs about launching including log from HelloWorldPlugin with text Hello world.

"},{"location":"micro_utils/repos/index.html","title":"Repos","text":"

Repositories in this library are unified interfaces to work with different types of standard repos:

"},{"location":"micro_utils/repos/index.html#crud","title":"CRUD","text":"

Default interface for any CRUD-oriented realization of repositories. This type of repos separated to three interfaces:

flowchart TB ReadCRUDRepo --> CRUDRepo WriteCRUDRepo --> CRUDRepo

CRUDRepo extends both ReadCRUDRepo and WriteCRUDRepo.

CRUD repos do not support forced placing of data by id when data is not in repo. That means, that you can\u2019t set data in repo by id which absent in the repository.

"},{"location":"micro_utils/repos/index.html#readcrudrepo","title":"ReadCRUDRepo","text":"

Contains read-only operations, such as getById, contains. This interface can\u2019t be observed because of it does not suppose any mutable operation.

"},{"location":"micro_utils/repos/index.html#writecrudrepo","title":"WriteCRUDRepo","text":"

Contains write-only operations, such as create, update. This interface can be observed via its flows:

Info

By default, all mutating operations consumes Lists of data (List<New> for create, List<Pair<Id, New>> for update and List<Id> for delete), but all they have their extension function-variations with one/two args (like create with New arg)

"},{"location":"micro_utils/repos/index.html#keyvalue","title":"KeyValue","text":"

Key-value repos has been created to support work with classic key-value stores, where keys are unique across all the repo when values are not unique. As well as all the others types of repos, this one have two basic types: ReadKeyValueRepo and WriteKeyValueRepo

"},{"location":"micro_utils/repos/index.html#readkeyvaluerepo","title":"ReadKeyValueRepo","text":"

Read repo provides functions like: contains, get or values.

"},{"location":"micro_utils/repos/index.html#writekeyvaluerepo","title":"WritekeyValueRepo","text":"

Contains write-only operations. This interface can be observed via its flows:

Info

By default, all mutating operations consumes some collections. For example, set require Map with Keys and Values and do not returns anything. Instead, it will throw notification via onNewValue flow

All the methods on WriteKeyValueRepo have their variances with pairs (for set) or plain varargs.

"},{"location":"micro_utils/repos/index.html#keyvalues","title":"KeyValues","text":"

This type of repos contains muliple Values by their unique Key. It is not guaranteed, that Values list by any Key will contains only unique values, but in most cases Values list will not contains copies/same objects.

"},{"location":"micro_utils/repos/index.html#readkeyvaluesrepo","title":"ReadKeyValuesRepo","text":"

Contains operations for work with value/values getting and checking. For example: count for checking of amount of all values in repo or values by key; get for getting of values by pagination.

"},{"location":"micro_utils/repos/index.html#writekeyvaluesrepo","title":"WriteKeyValuesRepo","text":"

Contains write-only operations. This interface can be observed via its flows:

Info

In difference with other repos, not all the methods of write key values repo require collections.

All the methods on WriteKeyValuesRepo have their variances with pairs (for set) or plain varargs.

"},{"location":"micro_utils/repos/inmemory.html","title":"In memory","text":"

In memory realizations contains several simple variants:

Each realization contains Write and Read parents.

There are several important moments:

"},{"location":"micro_utils/repos/inmemory.html#writemapcrudrepo-and-mapcrudrepo","title":"WriteMapCRUDRepo (and MapCRUDRepo)","text":"

It is an abstract repo with abstract functions: updateObject and createObject. Both functions require from realization to create Registered variant from incoming data and both will be called within repo locker.withWriteLock.

You may use functions MapCRUDRepo with passing the callbacks updateObject and createObject which will be used in their realizations of default MapCRUDRepo variant

"},{"location":"navigation/index.html","title":"Navigation","text":"

This library uses koin as preferred DI in MVVM part

Navigation is a library for simple management for your app views (or some other logics). In this library there are several important terms:

"},{"location":"navigation/index.html#work-explanation","title":"Work explanation","text":" Statuses

There are 4 real statuses:

In fact node will retrieve 6 changes of statuses:

flowchart TB New -.-> Create Create -.-> Created Created -.-> Start -.-> Started Started --> Resume --> Resumed Resumed --> Pause --> Started Started --> Stop --> Created Created --> Destroy Destroy --> New DashedLineLegendTitle(Dashed line) -.-> DashedLineLegend(Possible direction before `Created` state) SolidLineLegendTitle(Solid line) --> SolidLineLegend(Possible direction after `Created` state) class New navigation-new; class Destroyed navigation-new; class Created navigation-created; class Started navigation-started; class Resumed navigation-resumed;"},{"location":"navigation/index.html#nodes-behaviour","title":"Nodes behaviour","text":"

Let\u2019s see the next sample:

flowchart LR subgraph Nodes/Chains tree NodeN1(N1) NodeN2(N2) class NodeN1 navigation-started; class NodeN2 navigation-resumed; subgraph RootChain direction LR NodeN1 --> NodeN2 end class RootChain navigation-resumed; end

we may say several things about the sample above:

So, we would like to add new node in the end of stack:

flowchart LR subgraph Nodes/Chains tree NodeN1(N1) NodeN2(N2) NodeN3(N3) class NodeN1 navigation-started; class NodeN2 navigation-started; class NodeN3 navigation-resumed; subgraph RootChain direction LR NodeN1 --> NodeN2 NodeN2 --> NodeN3 end class RootChain navigation-resumed; end

As we can see, N3 became RESUMED and N2 PAUSED. Let\u2019s try to remove N3:

flowchart LR subgraph Nodes/Chains tree NodeN1(N1) NodeN2(N2) class NodeN1 navigation-started; class NodeN2 navigation-resumed; subgraph RootChain direction LR NodeN1 --> NodeN2 end class RootChain navigation-resumed; end"},{"location":"navigation/index.html#chains-behaviour","title":"Chains behaviour","text":"

So, let\u2019s continue with the sample above. Let\u2019s imagine, we need to add new subchain for N2 node. Whole tree will look like:

flowchart LR subgraph Nodes/Chains tree direction LR NodeN1(N1) NodeN2(N2) NodeN3(N3) class NodeN1 navigation-started; class NodeN2 navigation-resumed; class NodeN3 navigation-resumed; subgraph RootChain direction LR NodeN1 --> NodeN2 NodeN2 end NodeN2 --> N2Subchain subgraph N2Subchain direction LR NodeN3 end class RootChain navigation-resumed; class N2Subchain navigation-resumed; end

Here has been created new N2Subchain with N3 node. Both them resumed because of:

We may add new subchain to N1:

flowchart LR subgraph Nodes/Chains tree direction LR NodeN1(N1) NodeN2(N2) NodeN3(N3) NodeN4(N4) class NodeN1 navigation-started; class NodeN2 navigation-resumed; class NodeN3 navigation-resumed; class NodeN4 navigation-started; subgraph RootChain direction LR NodeN1 --> NodeN2 NodeN2 end NodeN1 --> N1Subchain NodeN2 --> N2Subchain subgraph N1Subchain direction LR NodeN4 end subgraph N2Subchain direction LR NodeN3 end class RootChain navigation-resumed; class N1Subchain navigation-started; class N2Subchain navigation-resumed; end

So, it has been added, but:

And now we may remove N2 node. This action will trigger next changes:

flowchart LR subgraph Changes subgraph OldNodesChainsTree [Old Nodes/Chains tree] direction TB OldNodeN1(N1) OldNodeN2(N2) OldNodeN3(N3) OldNodeN4(N4) class OldNodeN1 navigation-started; class OldNodeN2 navigation-created; class OldNodeN3 navigation-created; class OldNodeN4 navigation-started; subgraph OldRootChain [RootChain] direction TB OldNodeN1 --> OldNodeN2 OldNodeN2 end OldNodeN1 --> OldN1Subchain OldNodeN2 --> OldN2Subchain subgraph OldN1Subchain [N1Subchain] direction TB OldNodeN4 end subgraph OldN2Subchain [N2Subchain] direction TB OldNodeN3 end class OldRootChain navigation-resumed; class OldN1Subchain navigation-started; class OldN2Subchain navigation-created; end subgraph NewNodesChainsTree [New Nodes/Chains tree] direction TB NewNodeN1(N1) NewNodeN4(N4) class NewNodeN1 navigation-resumed; class NewNodeN4 navigation-resumed; subgraph NewRootChain [RootChain] direction TB NewNodeN1 end NewNodeN1 ---> NewN1Subchain subgraph NewN1Subchain [N1Subchain] direction TB NewNodeN4 end class NewRootChain navigation-resumed; class NewN1Subchain navigation-resumed; end %% OldNodesChainsTree -.-> NewNodesChainsTree OldNodeN1-.->|Become resumed| NewNodeN1 OldNodeN4-.->|Become resumed| NewNodeN4 end

What has happened:

  1. We solved to remove N2 node. Status is changing to stopped
  2. N2Subchain must be stopped
  3. N3 must be stopped as well

Stopping in context of navigation means destroying

"},{"location":"navigation/index.html#large-tree-sample","title":"Large tree sample","text":"flowchart TB NodeN1(N1) NodeN2(N2) NodeN3(N3) class NodeN1 navigation-started; class NodeN2 navigation-started; class NodeN3 navigation-resumed; subgraph RootChain direction TB NodeN1-->NodeN2 NodeN2-->NodeN3 end class RootChain navigation-resumed; NodeN4(N4) NodeN5(N5) NodeN6(N6) class NodeN4 navigation-started; class NodeN5 navigation-started; class NodeN6 navigation-started; subgraph N2Subchain direction TB NodeN4-->NodeN5 NodeN5-->NodeN6 end class N2Subchain navigation-started; NodeN2 --> N2Subchain NodeN7(N7) NodeN8(N8) class NodeN7 navigation-started; class NodeN8 navigation-resumed; subgraph N3Subchain direction TB NodeN7 --> NodeN8 end class N3Subchain navigation-resumed; NodeN3 --> N3Subchain NodeN9(N9) NodeN10(N10) class NodeN9 navigation-started; class NodeN10 navigation-resumed; subgraph N3Subchain2 direction TB NodeN9 --> NodeN10 end class N3Subchain2 navigation-resumed; NodeN3 --> N3Subchain2"},{"location":"navigation/getting-started.html","title":"Getting started (TBD)","text":"

Traditionally, you need to add dependency to your project. Currently, there are two types of artifacts:

Artifact Purpose Dependency Core Only necessary tools for your projects implementation \"dev.inmo:navigation.core:$navigation_version\" MVVM Model-View-ViewModel architecture tools + Core components implementation \"dev.inmo:navigation.mvvm:$navigation_version\""},{"location":"navigation/getting-started.html#get-started","title":"Get started","text":"

After you have added your dependency, you should initialize navigation. There are several important things:

  1. Config - it is an instance of any class which extending the NavigationNodeDefaultConfig in common case
  2. Factory - usually object which may create a node or some required part for node

For example: lets imagine that we have a node Main. Here what should we do to create a node and make it workable in navigation:

data class MainConfig(\n    // this id will be used to search an html element by id in JS\n    // and Fragment by tag in Android\n    override val id: String = \"main\"\n) : NavigationNodeDefaultConfig\n

Both JS and Android platforms require ViewModel for their MVVM node variants, but it can be common as well as MainConfig:

class MainViewModel(\n    node: NavigationNode<MainConfig, NavigationNodeDefaultConfig>\n) : ViewModel(\n    node\n)\n
"},{"location":"navigation/getting-started.html#js-part","title":"JS part","text":"
// Core variant without MVVM or Compose\nclass MainNode(\n    config: MainConfig,\n    chain: NavigationChain<NavigationNodeDefaultConfig>,\n) : JsNavigationNode<MainConfig, NavigationNodeDefaultConfig>(\n    chain,\n    config\n) {\n    // Some code\n    // In htmlElementStateFlow will be found `HTMLElement` where node should be binded\n}\n// MVVM Compose variant\nclass MainNodeView(\n    config: MainConfig,\n    chain: NavigationChain<NavigationNodeDefaultConfig>,\n) : View<MainConfig, MainViewModel>(\n    config,\n    chain\n) {\n    // Some code\n    // In htmlElementStateFlow will be found `HTMLElement` where node should be binded\n\n    @Composable\n    override onDraw() {\n        Text(\"Hello world\")\n    }\n}\n\nobject MainNodeFactory : NavigationNodeFactory<NavigationNodeDefaultConfig> {\n    override fun createNode(\n        navigationChain: NavigationChain<NavigationNodeDefaultConfig>,\n        config: NavigationNodeDefaultConfig\n    ): NavigationNode<out NavigationNodeDefaultConfig, NavigationNodeDefaultConfig>? = if (config is MainConfig) {\n        MainNode(config, navigationChain) // Or `MainNodeView(config, chain)` for MVVM\n    } else {\n        null\n    }\n}\n

Data below is under TBD

"},{"location":"navigation/getting-started.html#android","title":"Android","text":"

In Android there is one important note: you will not directly work with nodes. In fact it will be required to create special NodeFragment:

// Core variant\nclass MainFragment : NodeFragment<MainConfig, NavigationNodeDefaultConfig>() {\n    // Your code\n    // Here will be available: node with type `AndroidFragmentNode`, config: `MainConfig`\n}\n// MVVM Variant\nclass MainViewFragment : ViewFragment<MainViewModel, MainConfig>() {\n    // Will be available also `viewModel` via koin `lazyInject`\n    override val viewModelClass\n        get() = MainViewModel::class\n}\n

Initialization is different on the platforms, so, lets take a look at each one.

"},{"location":"navigation/getting-started.html#js","title":"JS","text":"

In JavaScript it looks like:

initNavigation<NavigationNodeDefaultConfig>(\n    ConfigHolder.Chain( // (1)\n        ConfigHolder.Node( // (2)\n            MainConfig(), // (3)\n            null, // (4)\n            listOf() // (5)\n        ),\n    ),\n    configsRepo = CookiesNavigationConfigsRepo( // (6)\n        Json {\n            ignoreUnknownKeys = true\n            serializersModule = SerializersModule {\n                polymorphic(NavigationNodeDefaultConfig::class, MainConfig::class, MainConfig.serializer()) // (7)\n            }\n        },\n        ConfigHolder.serializer(NavigationNodeDefaultConfig::class.serializer())\n    ),\n    dropRedundantChainsOnRestore = true, // (8)\n    nodesFactory = MainNodeFactory, // (9)\n)\n
  1. Creating of default root chain config holder. It must be root chain because of the chain work with statuses changes
  2. Creating of default root node config holder. This type contains config of the first node, its subnode and subchains lists
  3. Default root config
  4. Subnode of root node. In this case it is null, but can be any ConfigHolder.Node
  5. Subchains of default root node
  6. Configurations changes repo saver. By default it is cookies (localStorage) store
  7. Register config for serialization to let configs repo serializer to know how to serialize MainConfig
  8. Flag that the chains without any node will be dropped automatically
  9. In fact here can be factory aggregator, for example:
    val factories: List<NavigationNodeFactory<NavigationNodeDefaultConfig>>\nNavigationNodeFactory<NavigationNodeDefaultConfig> { chainHolder, config ->\n    factories.firstNotNullOfOrNull { it.createNode(chainHolder, config) }\n}\n
"},{"location":"plagubot/index.html","title":"PlaguBot","text":"

PlaguBot is a small framework for unifying developing of modules of bots. It is built with two parts:

"},{"location":"plagubot/index.html#plugin","title":"Plugin","text":"

Plugin is a partially independent part of bot. Plugin have several parts:

Plugin realization should be an object or class with empty constructor.

"},{"location":"plagubot/index.html#bot","title":"Bot","text":"

Most important of bot is main function (full reference: dev.inmo.plagubot.AppKt). It consumes one argument - path to config.

Bot is initializing with the next algorithm:

flowchart TB main[\"Main\"] Join[\"Endless join bot work\"] subgraph ConfigReading direction LR ConfigJsonParsing[\"Parsing to Json\"] ConfigParsing[\"Parsing to global config\"] ConfigJsonParsing --> ConfigParsing end ConfigReading[\"Reading of config\"] BotConstructorCalling[\"Calling of PlaguBot constructor\"] subgraph BotStart direction TB BotStartKoinAppInit[\"Initialization of koin app\"] subgraph BotStartSetupDI direction LR subgraph BotStartSetupDIPutDefaults[\"Put defaults in DI\"] direction LR BotStartSetupDIPutDefaultsConfig[\"Config\"] BotStartSetupDIPutDefaultsPluginsList[\"Plugins list\"] BotStartSetupDIPutDefaultsDatabaseConfig[\"Database Config\"] BotStartSetupDIPutDefaultsDefaultJson[\"Default Json\"] BotStartSetupDIPutDefaultsPlagubot[\"PlaguBot itself\"] BotStartSetupDIPutDefaultsTelegramBot[\"TelegramBot\"] end BotStartSetupDIIncludes[\"`Synchronous (in queue) registration of all plugins __setupDI__ modules`\"] BotStartSetupDIPutDefaults --> BotStartSetupDIIncludes end BotStartKoinAppStart[\"`Starting of koin application. Since this step all modules from __setupDI__ of plugins will be available`\"] subgraph BotStartBehaviourContextInitialization[\"Initialization of behaviour context\"] direction TB BotStartBehaviourContextInitializationStatesManager[\"`Get from DI or create default **DefaultStatesManagerRepo**`\"] BotStartBehaviourContextInitializationStatesManagerRepo[\"`Get from DI or create default **StatesManagerRepo**`\"] BotStartBehaviourContextInitializationStatesManagerUsedCondition{\"Is the default one used?\"} BotStartBehaviourContextInitializationOnStartConflictsResolver[\"Getting of all OnStartContextsConflictResolver\"] BotStartBehaviourContextInitializationOnUpdateConflictsResolver[\"Getting of all OnUpdateContextsConflictResolver\"] BotStartBehaviourContextInitializationStateHandlingErrorHandler[\"`Get from DI or create default **StateHandlingErrorHandler**`\"] subgraph BotStartBehaviourContextInitializationSetupPlugins[\"Plugins bot functionality init\"] BotStartBehaviourContextInitializationSetupPluginsSetupBotPlugin[\"`Call **setupBotPlugin** for each plugin`\"] end BotStartBehaviourContextInitializationStatesManager --> BotStartBehaviourContextInitializationStatesManagerUsedCondition BotStartBehaviourContextInitializationStatesManagerUsedCondition --\"Yes\"--> BotStartBehaviourContextInitializationStatesManagerRepo BotStartBehaviourContextInitializationStatesManagerUsedCondition --\"No\"--> BotStartBehaviourContextInitializationStateHandlingErrorHandler BotStartBehaviourContextInitializationStatesManagerRepo --> BotStartBehaviourContextInitializationOnStartConflictsResolver BotStartBehaviourContextInitializationOnStartConflictsResolver --> BotStartBehaviourContextInitializationOnUpdateConflictsResolver BotStartBehaviourContextInitializationOnUpdateConflictsResolver --> BotStartBehaviourContextInitializationStateHandlingErrorHandler BotStartBehaviourContextInitializationStateHandlingErrorHandler --> BotStartBehaviourContextInitializationSetupPlugins end BotStartDeleteWebhook[\"Delete webhooks\"] BotStartStartLongPolling[\"Start long polling\"] BotStartKoinAppInit --> BotStartSetupDI BotStartSetupDI --> BotStartKoinAppStart BotStartKoinAppStart --> BotStartBehaviourContextInitialization BotStartBehaviourContextInitialization --> BotStartDeleteWebhook BotStartDeleteWebhook --> BotStartStartLongPolling end main --> ConfigReading ConfigReading --> BotConstructorCalling BotConstructorCalling --> BotStart BotStart --> Join"},{"location":"plagubot/opportunities_out_of_the_box.html","title":"Opportunities out of the box","text":"

There are several important opportunities out of the box:

"},{"location":"plagubot/opportunities_out_of_the_box.html#database-access","title":"Database access","text":"

You may access database in your plugin via koin in setupBotPlugin or as parameter in setupDI:

object YourPlugin : Plugin {\n    // ...\n    override fun Module.setupDI(\n        database: Database, // database\n        params: JsonObject\n    ) {\n        // ...\n    }\n}\n

It is simple Exposed database and you may use it in your tables.

"},{"location":"plagubot/opportunities_out_of_the_box.html#config-access","title":"Config access","text":"

As you may see, in the setupDI function we also have params parameter with source configuration json. In case you wish to declare and work with your own config in plugin, you may use next snippet:

object YourPlugin : Plugin {\n    @Serializable\n    data class MyConfig(\n        val param1: String,\n        val param2: Int,\n    )\n    // ...\n    override fun Module.setupDI(\n        database: Database, // database\n        params: JsonObject\n    ) {\n        single {\n            get<Json>().decodeFromJsonElement(MyConfig.serializer(), params) // register from root (1)\n        }\n        // OR\n        single {\n            get<Json>().decodeFromJsonElement(MyConfig.serializer(), params[\"yourplugin\"]!!) // register from field \"yourplugin\" (2)\n        }\n        // ...\n    }\n\n    override suspend fun BehaviourContext.setupBotPlugin(\n        koin: Koin\n    ) {\n        koin.get<MyConfig>() // getting of registered config\n    }\n}\n
  1. In this case your config will looks like:
    {\n  \"params1\": \"SomeString\",\n  \"params2\": 42\n}\n
  2. In this case your config will looks like:
    {\n  \"yourplugin\": {\n    \"params1\": \"SomeString\",\n    \"params2\": 42\n  }\n}\n
"},{"location":"plagubot/opportunities_out_of_the_box.html#bot-setup","title":"Bot setup","text":"

Out of the box you may setup several things in bot:

  1. For this use next code in setupDI:
    // Your plugin\n    override fun Module.setupDI(database: Database, params: JsonObject) {\n        single<StatesManager<State>> {\n            // Your StatesManager<State> initialization\n        }\n    }\n
  2. For this use next code in setupDI:
    // Your plugin\n    override fun Module.setupDI(database: Database, params: JsonObject) {\n        single<DefaultStatesManagerRepo<State>> {\n            // Your DefaultStatesManagerRepo<State> initialization\n        }\n    }\n
  3. You may declare any amount of OnStartContextsConflictResolver. PlaguBot will take first non-null result of resolvers from DI and use in default states manager. To declare, use next snippet:
    // Your plugin\n    override fun Module.setupDI(database: Database, params: JsonObject) {\n        singleWithRandomQualifier<OnStartContextsConflictResolver> {\n            OnStartContextsConflictResolver { old, new ->\n                // null|true|false\n            }\n        }\n    }\n
  4. You may declare any amount of OnUpdateContextsConflictResolver. PlaguBot will take first non-null result of resolvers from DI and use in default states manager. To declare, use next snippet:
    // Your plugin\n    override fun Module.setupDI(database: Database, params: JsonObject) {\n        singleWithRandomQualifier<OnUpdateContextsConflictResolver> {\n            OnUpdateContextsConflictResolver { old, new, currentStateOnContext ->\n                // null|true|false\n            }\n        }\n    }\n
  5. You may declare only one StateHandlingErrorHandler<State>. This handler will be called each time when some state will be handled with exception and may return null or new state instead old one:
    // Your plugin\n    override fun Module.setupDI(database: Database, params: JsonObject) {\n        single<StateHandlingErrorHandler<State>> {\n            StateHandlingErrorHandler<State> { state, throwable ->\n                // null or State\n            }\n        }\n    }\n
"},{"location":"services/index.html","title":"Services information","text":"

There are several public services I am hosting or have created:

  1. I am using this tool in all my libraries :)
"},{"location":"services/index.html#tools","title":"Tools","text":""},{"location":"services/index.html#services","title":"Services","text":""},{"location":"services/index.html#kdocs","title":"KDocs","text":""},{"location":"tgbotapi/index.html","title":"TelegramBotAPI","text":"

Hello! This is a set of libraries for working with Telegram Bot API.

"},{"location":"tgbotapi/index.html#examples","title":"Examples","text":"

There are several things you need to do to launch examples below:

More including instructions available here. Other configuration examples:

"},{"location":"tgbotapi/index.html#most-common-example","title":"Most common example","text":"
suspend fun main() {\n  val bot = telegramBot(TOKEN)\n\n  bot.buildBehaviourWithLongPolling {\n    println(getMe())\n\n    onCommand(\"start\") {\n      reply(it, \"Hi:)\")\n    }\n  }.join()\n}\n

In this example you will see information about this bot at the moment of starting and answer with Hi:) every time it gets message /start

"},{"location":"tgbotapi/index.html#handling-only-last-messages","title":"Handling only last messages","text":"
suspend fun main() {\n  val bot = telegramBot(TOKEN)\n\n  val flowsUpdatesFilter = FlowsUpdatesFilter()\n  bot.buildBehaviour(flowUpdatesFilter = flowsUpdatesFilter) {\n    println(getMe())\n\n    onCommand(\"start\") {\n      reply(it, \"Hi:)\")\n    }\n\n    retrieveAccumulatedUpdates(this).join()\n  }\n}\n

The main difference with the previous example is that bot will get only last updates (accumulated before bot launch and maybe some updates it got after launch)

"},{"location":"tgbotapi/index.html#build-a-little-bit-more-complex-behaviour","title":"Build a little bit more complex behaviour","text":"
suspend fun main() {\n  val bot = telegramBot(TOKEN)\n\n  bot.buildBehaviourWithLongPolling {\n    println(getMe())\n\n    val nameReplyMarkup = ReplyKeyboardMarkup(\n      matrix {\n        row {\n          +SimpleKeyboardButton(\"nope\")\n        }\n      }\n    )\n    onCommand(\"start\") {\n      val photo = waitPhoto(\n        SendTextMessage(it.chat.id, \"Send me your photo please\")\n      ).first()\n\n      val name = waitText(\n        SendTextMessage(\n          it.chat.id,\n          \"Send me your name or choose \\\"nope\\\"\",\n          replyMarkup = nameReplyMarkup\n        )\n      ).first().text.takeIf { it != \"nope\" }\n\n      sendPhoto(\n        it.chat,\n        photo.mediaCollection,\n        entities = buildEntities {\n          if (name != null) regular(name) // may be collapsed up to name ?.let(::regular)\n        }\n      )\n    }\n  }.join()\n}\n
"},{"location":"tgbotapi/index.html#more-examples","title":"More examples","text":"

You may find examples in this project. Besides, you are always welcome in our chat.

"},{"location":"tgbotapi/faq.html","title":"FAQ","text":""},{"location":"tgbotapi/faq.html#what-is-the-error-failed-to-load-class-orgslf4jimplstaticloggerbinder","title":"What is the error Failed to load class \"org.slf4j.impl.StaticLoggerBinder\"?","text":"
SLF4J: Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".\nSLF4J: Defaulting to no-operation (NOP) logger implementation\nSLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.\n

This error is just a warning about the absence of slf4j setup. You may fix this error by following to stackoverflow answer

"},{"location":"tgbotapi/faq.html#how-to-filter-updates-in-some-part-of-behaviourbuilder","title":"How to filter updates in some part of BehaviourBuilder?","text":"

You may create subcontext with BehaviourBuilder.createSubContextAndDoWithUpdatesFilter and pass there updatesUpstreamFlow parameter with any operations over parent behaviour builder:

buildBehaviourWithLongPolling {\n    createSubContextAndDoWithUpdatesFilter(\n        updatesUpstreamFlow = filter { /* some condition */ },\n        stopOnCompletion = false // disable stopping of sub context after setup\n    ) {\n        onCommand() //...\n    }\n}\n
"},{"location":"tgbotapi/faq.html#additional-info","title":"Additional info","text":""},{"location":"tgbotapi/faq.html#cases","title":"Cases","text":""},{"location":"tgbotapi/logs.html","title":"Logging","text":"

In this library we are using KSLog for logging of events in telegram bots. There are several ways to set it up and configure.

// (1)\nsetDefaultKSLog(\n    KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->\n        println(defaultMessageFormatter(level, tag, message, throwable))\n    }\n)\n\n// (2)\nDefaultKTgBotAPIKSLog = KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->\n    println(defaultMessageFormatter(level, tag, message, throwable))\n}\n\n// (3)\nval bot = telegramBot(YOUR_TOKEN) {\n    logger = KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->\n        println(defaultMessageFormatter(level, tag, message, throwable))\n    }\n}\n
  1. This variant will set GLOBAL DEFAULT logger. For example, if you will use somewhere TagLogger, it will use KSLog.default under the hood
  2. All the bots created after this setup will use new logger until more specified logger configured (see below)
  3. Passing of logger variable to the KtorRequestsExecutor or one of factories telegrabBot will lead to granular setup of logging
"},{"location":"tgbotapi/dsls/keyboards.html","title":"Keyboards","text":"

In the telegram system there are two types of keyboards:

Reply Inline Keyboard for each user in the chat Keyboard linked to the certain message

Low-level way to create keyboard looks like in the next snippet:

ReplyKeyboardMarkup(\n    matrix {\n        row {\n            add(SimpleKeyboardButton(\"Simple text\"))\n            // ...\n        }\n        // ...\n    }\n)\n

In case you wish to create inline keyboard, it will look like the same as for reply keyboard. But there is another way. The next snippet will create the same keyboard as on the screenshots above:

// reply keyboard\nreplyKeyboard {\n    row {\n        simpleButton(\"7\")\n        simpleButton(\"8\")\n        simpleButton(\"9\")\n        simpleButton(\"*\")\n    }\n    row {\n        simpleButton(\"4\")\n        simpleButton(\"5\")\n        simpleButton(\"6\")\n        simpleButton(\"/\")\n    }\n    row {\n        simpleButton(\"1\")\n        simpleButton(\"2\")\n        simpleButton(\"3\")\n        simpleButton(\"-\")\n    }\n    row {\n        simpleButton(\"0\")\n        simpleButton(\".\")\n        simpleButton(\"=\")\n        simpleButton(\"+\")\n    }\n}\n\n// inline keyboard\ninlineKeyboard {\n    row {\n        dataButton(\"Get random music\", \"random\")\n    }\n    row {\n        urlButton(\"Send music to friends\", \"https://some.link\")\n    }\n}\n
"},{"location":"tgbotapi/dsls/live-location.html","title":"Live Location","text":"

Bot API allows you to send live locations and update them during their lifetime. In this library there are several ways to use this API:

"},{"location":"tgbotapi/dsls/live-location.html#sendlivelocation","title":"sendLiveLocation","text":"

In the Bot API there is no independent sendLiveLocation method, instead it is suggested to use sendLocation with setting up live_period. In this library in difference with original Bot API live location is special request. It was required because of in fact live locations and static locations are different types of location info and you as bot developer may interact with them differently.

Anyway, in common case the logic looks like:

"},{"location":"tgbotapi/dsls/live-location.html#startlivelocation","title":"startLiveLocation","text":"

In difference with sendLiveLocation, startLiveLocation using LiveLocationProvider. With this provider you need not to handle chat and message ids and keep some other data for location changes. Instead, you workflow with provider will be next:

Besides, LiveLocationProvider contains different useful parameters about live location

"},{"location":"tgbotapi/dsls/live-location.html#handlelivelocation","title":"handleLiveLocation","text":"

This way of live locations handling is based on coroutines Flow and allow you to pass some external Flow with EditLiveLocationInfo. So, workflow:

See our example to get more detailed sample

"},{"location":"tgbotapi/dsls/text.html","title":"Text","text":"

For the text creating there are several tools. The most simple one is to concatenate several text sources to make list of text sources as a result:

val sources = \"Regular start of text \" + bold(\"with bold part\") + italic(\"and italic ending\")\n

But there is a little bit more useful way: entities builder:

val items = (0 until 10).map { it.toString() }\nbuildEntities(\" \") {// optional \" \" auto separator which will be pasted between text sources\n    +\"It is regular start too\" + bold(\"it is bold as well\")\n    items.forEachIndexed { i, item ->\n        if (i % 2) {\n            italic(item)\n        } else {\n            strikethrough(item)\n        }\n    }\n}\n

In the code above we are creating an items list just for demonstrating that inside of buildEntities body we may use any operations for cunstructing our result list of TextSources. As a result, will be created the list which will looks like in telegram as \u201cIt is regular start too it is bold as well 0 ~~1~~ 2 ~~3~~ 4 ~~5~~ 6 ~~7~~ 8 ~~9~~\u201d.

"},{"location":"tgbotapi/guides/keyboards.html","title":"Keyboards Guide","text":"

This guide will help you choose the right keyboard for your needs and show you various API facilities available in the library to support your choice.

"},{"location":"tgbotapi/guides/keyboards.html#introduction","title":"Introduction","text":""},{"location":"tgbotapi/guides/keyboards.html#keyboard-types","title":"Keyboard Types","text":"

The first thing you need to know is that there are two types of keyboards available in the Telegram Bot API: reply and inline keyboards.

Resize option

In the screenshots above (and in the most others) you may see usage of reply keyboards without resize_keyboard. In case you will use resize_keyboard = true the keyboard will be smaller.

Note the differences in the way these keyboards are shown to a user.

A reply keyboard is shown under the message input field. It replaces the device\u2019s native input method on a mobile device.

An inline keyboard is shown as a part of the message in the chat.

"},{"location":"tgbotapi/guides/keyboards.html#simple-keyboard-interactions","title":"Simple Keyboard Interactions","text":"

When a user clicks on a simple reply keyboard button, its text is just sent in the chat.

When a user clicks on a simple inline keyboard button, nothing is sent to the chat. Instead, a callback query (a fancy way to say \u201ca request\u201d) is sent directly to the bot and the button is highlighted. It will stay highlighted until the bot acks the callback.

It\u2019s a common mistake to forget to handle callback queries

It leads to the buttons being highlighted for long periods of time, which leads to a bad user experience. Don\u2019t forget to handle these callbacks!

As new messages arrive, a reply keyboard will stay there, while the inline keyboard will stick to the message and move with it.

Ups\u2026 The reply keyboard is now far away from the message it was sent with.

Actually, they are two different unrelated entities now: the original message and the reply keyboard. A reply keyboard persists until you explicitly remove it or replace it with a different one.

It\u2019s a common mistake to forget to remove or replace reply keyboards

It leads to the keyboards being shown forever. Don\u2019t forget to remove reply keyboards when you don\u2019t need them anymore!

You also may use option one_time_keyboard and the keyboard will be automatically removed after user interaction

An inline keyboard could also be removed or changed by editing the original message it was attached to.

"},{"location":"tgbotapi/guides/keyboards.html#extended-keyboard-interactions","title":"Extended Keyboard Interactions","text":"

Keyboards are not limited to text only. They could be used to ask users for different things, like payments, locations, phone numbers, etc. They could be used to open arbitrary URLs or web apps. Telegram clients process these buttons and interact with the users in the appropriate ways.

For the full list of options, see the official documentation on reply and inline keyboards.

"},{"location":"tgbotapi/guides/keyboards.html#basic-api-classes","title":"Basic API & Classes","text":"

Now, that you know the basics, let\u2019s see how to use the library.

"},{"location":"tgbotapi/guides/keyboards.html#keyboards","title":"Keyboards","text":"

In Telegram Bot API keyboards are sent to the user as a part of an interaction via the reply_markup parameter. More specifically, this parameter is available:

Tip

editMessageReplyMarkup is specifically designed to edit a message\u2019s inline keyboard.

Sending inline keyboards is also supported in inline mode through the reply_markup parameter of the InlineQueryResult type and its inheritors. However, this inline mode is unrelated to the inline keyboards.

The reply_markup parameter accepts four different types. Two of them \u2014 ReplyKeyboardMarkup and InlineKeyboardMarkup \u2014 correspond to the reply and inline keyboards respectively. The ReplyKeyboardRemove type is used to remove reply keyboards, but it\u2019s not a keyboard itself. The last one, ForceReply, is used to force users to reply to the bot. It is not a keyboard either, but yet another dirty hack employed by the Telegram Bot API.

Now, in the library, the WithReplyMarkup is a marker interface for all the interactions which could have a replyMarkup (represents reply_markup) parameter. It is extended by the ReplyingMarkupSendMessageRequest, and then, finally, by classes like SendTextMessage. This, basically, corresponds to the Telegram Bot API.

Note

You may see all the inheritors of WithReplyMarkup interfaces in the corresponding KDoc

The other way to send a keyboard is through the replyMarkup parameter of the numerous extension methods, like sendMessage. Those are just convenient wrappers around general interaction classes, like the aforementioned SendTextMessage.

"},{"location":"tgbotapi/guides/keyboards.html#buttons","title":"Buttons","text":"

As we already know, keyboards consist of buttons. Button classes reside in the dev.inmo.tgbotapi.types.buttons package.

The base class for the reply keyboard buttons is the KeyboardButton. The base class for the inline keyboard buttons is the InlineKeyboardButton.

See their inheritors for the full list of the available buttons. The names are pretty self-explanatory and correspond to the Telegram Bot API.

For example, to send a simple reply keyboard button, use the SimpleKeyboardButton class. To request a contact from the user through the reply, use the RequestContactKeyboardButton class. To attach a URL button to the message, use the URLInlineKeyboardButton. And to attach a callback button, use the CallbackDataInlineKeyboardButton.

You get the idea.

So, to send a reply keyboard use the following code:

bot.sendMessage(\n    chatId = chat,\n    text = \"What is the best Kotlin Telegram Bot API library?\",\n    replyMarkup = ReplyKeyboardMarkup(\n        keyboard = listOf(\n            listOf(\n                SimpleKeyboardButton(\"ktgbotapi\"),\n            ),\n        )\n    )\n)\n

And here is how you send a basic inline keyboard:

bot.sendMessage(\n    chatId = chat,\n    text = \"ktgbotapi is the best Kotlin Telegram Bot API library\",\n    replyMarkup = InlineKeyboardMarkup(\n        keyboard = listOf(\n            listOf(\n                CallbackDataInlineKeyboardButton(\"I know\", \"know\"),\n                URLInlineKeyboardButton(\"Learn more\", \"https://github.com/InsanusMokrassar/ktgbotapi\")\n            ),\n        )\n    ),\n)\n

When we\u2019re done with this simple quiz, we can remove the keyboard with the following code:

bot.sendMessage(\n    chatId = chat,\n    text = \"You're goddamn right!\",\n    replyMarkup = ReplyKeyboardRemove()\n)\n

Note

Don\u2019t forget to remove the reply keyboards!

"},{"location":"tgbotapi/guides/keyboards.html#matrices","title":"Matrices","text":"

Buttons in keyboards are arranged in matrices, i.e. two-dimensional arrays, or, to say in layperson\u2019s terms, rows and columns. In contrast to the matrices you\u2019ve learned in school, keyboards are not always necessarily square. Try it:

bot.sendMessage(\n    chatId = chat,\n    text = \"In contrast to the matrices you've learned in school, keyboards are not always necessary square.\",\n    replyMarkup = InlineKeyboardMarkup(\n        keyboard = listOf(\n            listOf(\n                CallbackDataInlineKeyboardButton(\"1\", \"1\"),\n                CallbackDataInlineKeyboardButton(\"2\", \"2\"),\n                CallbackDataInlineKeyboardButton(\"3\", \"3\"),\n            ),\n            listOf(\n                CallbackDataInlineKeyboardButton(\"4\", \"4\"),\n                CallbackDataInlineKeyboardButton(\"5\", \"5\"),\n            ),\n            listOf(\n                CallbackDataInlineKeyboardButton(\"6\", \"6\"),\n            )\n        )\n    )\n)\n

This way of building matrices is not very convenient, so the library provides a few eloquent DSLs to simplify that.

First, there are matrix and row, so the keyboard above can be built like this:

bot.sendMessage(\n    chatId = chat,\n    text = \"DSLs are sweet!\",\n    replyMarkup = InlineKeyboardMarkup(\n        keyboard = matrix {\n            row {\n                +CallbackDataInlineKeyboardButton(\"1\", \"1\")\n                +CallbackDataInlineKeyboardButton(\"2\", \"2\")\n                +CallbackDataInlineKeyboardButton(\"3\", \"3\")\n            }\n            row(\n                CallbackDataInlineKeyboardButton(\"4\", \"4\"),\n                CallbackDataInlineKeyboardButton(\"5\", \"5\"),\n            )\n            row {\n                +CallbackDataInlineKeyboardButton(\"6\", \"6\")\n            }\n        },\n    )\n)\n

Note

Those plus signs are mandatory.

Note

There are two different row functions here. Can you spot the difference?

A single-row matrix can be built with a flatMatrix:

flatMatrix {\n    +CallbackDataInlineKeyboardButton(\"1\", \"1\")\n    +CallbackDataInlineKeyboardButton(\"2\", \"2\")\n    +CallbackDataInlineKeyboardButton(\"3\", \"3\")\n    +CallbackDataInlineKeyboardButton(\"4\", \"4\")\n    +CallbackDataInlineKeyboardButton(\"5\", \"5\")\n}\n

But the most convenient way to build a simple keyboard is to use the constructor-like methods: InlineKeyboardMarkup and ReplyKeyboardMarkup. Note, that they are named just like the corresponding constructor, but take a vararg of buttons. They create flat matrices, i.e. single rows.

"},{"location":"tgbotapi/guides/keyboards.html#keyboards-dsl","title":"Keyboards DSL","text":"

Finally, there are inlineKeyboard and replyKeyboard

DSL methods above rely on Kotlin\u2019s feature of receivers and extensions. So, the magic is done by MatrixBuilder and RowBuilder. That\u2019s why you must use the plus sign to add buttons to the matrix: it\u2019s just an overloaded operator call, another cool Kotlin feature widely used to create sweet DSLs.

Another bonus of using these DSLs is button builders, like payButton, dataButton, and urlButton:

bot.sendMessage(\n    chatId = chat,\n    text = \"All in one!\",\n    replyMarkup = InlineKeyboardMarkup(\n        keyboard = matrix {\n            row {\n                payButton(\"Send money\")\n                dataButton(\"Ok\", \"ok\")\n                urlButton(\"Google\", \"https://google.com\")\n            }\n        },\n    )\n)\n

Reply keyboard builders provide similar extensions, e.g. requestLocationButton.

So, choose the style you like \u2014 from plain Kotlin lists to sweet DSLs \u2014 and use it!

"},{"location":"tgbotapi/guides/keyboards.html#working-with-keyboards","title":"Working with keyboards","text":"

Working with keyboards is not something special in Telegram Bot API. As you have already seen, keyboards are just message parameters. Similarly, keyboard interactions are represented by regular Updates. I.e. when a user interacts with a keyboard, the bot receives an update.

On the other hand, the library is heavily typed, so the actual type of update you would receive varies.

"},{"location":"tgbotapi/guides/keyboards.html#reply-keyboards","title":"Reply keyboards","text":"

As it was said, reply keyboards cause Telegram clients to send regular messages back to the bot. Peruse this example:

bot.buildBehaviourWithLongPolling {\n    bot.sendMessage(\n        chatId = chat,\n        text = \"\ud83d\udc6e Turn in your accomplices or be prepared for a lengthy \ud83c\udf46 incarceration \u26d3 \ud83d\udc4a \u203c\",\n        replyMarkup = replyKeyboard {\n            +SimpleKeyboardButton(\n                \"I ain't no rat! \ud83d\udeab\ud83d\udc00\ud83e\udd10\ud83d\ude45\"\n            )\n            +RequestUserKeyboardButton(\n                \"Rat out \ud83d\udc00 a friend \ud83d\udc64\",\n                KeyboardButtonRequestUser.Common(RequestId.random())\n            )\n            +RequestChatKeyboardButton(\n                \"Rat out \ud83d\udc00 a group of friends \ud83d\udc65\",\n                KeyboardButtonRequestChat.Group(RequestId.random())\n            )\n        }\n    )\n\n    onText { message: CommonMessage<TextContent> ->\n        assert(message.text == \"I ain't no rat! \ud83d\udeab\ud83d\udc00\ud83e\udd10\ud83d\ude45\")\n        bot.reply(\n            to = message,\n            text = \"Good, you're going to jail alone! \u26d3\ud83e\uddd1\u26d3\",\n            replyMarkup = ReplyKeyboardRemove()\n        )\n    }\n\n    onUserShared { message: PrivateEventMessage<UserShared> ->\n        bot.reply(\n            to = message,\n            text = \"Haha, you and you friend are both going to jail! \u26d3\ud83d\udc6c\u26d3\",\n            replyMarkup = ReplyKeyboardRemove()\n        )\n    }\n\n    onChatShared { message: PrivateEventMessage<ChatShared> ->\n        bot.reply(\n            to = message,\n            text = \"Haha, now you're all going to jail! \u26d3\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66\u26d3\",\n            replyMarkup = ReplyKeyboardRemove()\n        )\n    }\n}.join()\n

Note

Read more about buildBehaviourWithLongPolling here

I hope you get the idea: the bot acts like a cop and asks the user to rat out his friends via a reply keyboard (it\u2019s an imaginary situation, of course). The user may refuse to cooperate, rat out a single friend or the whole imaginary group. The bot receives the user\u2019s choices as regular updates, the code above has explicit types (generally optional in Kotlin) and an assert to demonstrate this.

And here is how it works (the user selects the options in the order):

Note how you handle reply keyboards: you process regular messages. For instance, a simple text button sends a regular text message indistinguishable from a case when a user simply types the same text manually.

And don\u2019t be a rat in real life: remove the keyboards with the ReplyKeyboardRemove after you\u2019ve received the input! Otherwise, a keyboard will stay there indefinitely.

"},{"location":"tgbotapi/guides/keyboards.html#inline-keyboards","title":"Inline keyboards","text":"

Finally, to master the keyboards, you need to know how to handle the inline ones.

Again, let\u2019s explore the example. Imagine you\u2019re making a quiz where users are given a question and a set of answers. Additionally, users are given a link to the wiki page to help with the question and a Google button.

The quiz could be implemented this way:

// A simple data class to represent a question\nval question = Question(\n    image = \"https://upload.wikimedia.org/wikipedia/commons/a/a5/Tsunami_by_hokusai_19th_century.jpg\",\n    question = \"Who painted this?\",\n    answers = listOf(\n        Answer(\"Hokusai\", correct = true),\n        Answer(\"Sukenobu\"),\n        Answer(\"Ch\u014dshun\"),\n        Answer(\"Kiyonobu I\"),\n    ),\n    wiki = \"https://en.wikipedia.org/wiki/Ukiyo-e\",\n)\n\nbot.buildBehaviourWithLongPolling {\n    bot.sendPhoto(\n        chatId = chat,\n        fileId = InputFile.fromUrl(question.image),\n        text = question.question,\n        replyMarkup = inlineKeyboard {\n            // First row: answers\n            row {\n                for (answer in question.answers.shuffled()) {\n                    dataButton(\n                        text = answer.answer,\n                        data = \"${answer.answer}:${answer.correct}\",\n                    )\n                }\n            }\n\n            // Second row: help buttons\n            row {\n                urlButton(\"Wiki \ud83d\udc81\", question.wiki)\n                webAppButton(\"Google \ud83d\udd0d\", \"https://google.com\")\n            }\n        }\n    )\n\n    onDataCallbackQuery { callback: DataCallbackQuery ->\n        val (answer, correct) = callback.data.split(\":\")\n\n        if (correct.toBoolean()) {\n            bot.answerCallbackQuery(\n                callback,\n                text = \"$answer is a \u2705 correct answer!\",\n                showAlert = true\n            )\n        } else {\n            bot.answerCallbackQuery(\n                callback,\n                text = \"\u274c Try again, $answer is not a correct answer\u2026\",\n                showAlert = true\n            )\n        }\n    }\n}.join()\n

A few important things to note here.

First, the data buttons (they have the CallbackDataInlineKeyboardButton type, but in the code we used a neat DSL) must have unique data. If the data is not unique, Telegram clients will highlight all the buttons with the same data when a user clicks on one of them. Guess how I know that? Well, it\u2019s not in the docs, so trial and error is the only way to learn it (and many other things about the Telegram Bot API).

Second, the way you handle inline keyboards is different from the way you handle reply keyboards. Bot API will send updates with a callback_query field populated. This field, of a CallbackQuery type, represents incoming callbacks from callback buttons in inline keyboards. The library turns them into multiple callback types, like the DataCallbackQuery we used in the example. Finally, to handle these callbacks you could use onDataCallbackQuery. Alternatively, if you\u2019re not using any DSLs, you have to handle the CallbackQueryUpdate update type.

Third, the buttons got highlighted when a user clicks on them. When you\u2019re done with the callback, you need to answer it, by using the answerCallbackQuery function. Otherwise, the button will remain highlighted. Telegram clients will eventually remove the highlight, but it\u2019s still frustrating.

Finally, you could choose between two styles of acknowledgment: a simple toast-like message or a modal alert. The showAlert flag controls this behavior.

And here is the demo of the quiz:

"},{"location":"tgbotapi/guides/keyboards.html#conclusion","title":"Conclusion","text":"

Today we\u2019ve learned how to use keyboards in Telegram bots. There are two types of keyboards: reply and inline. Reply keyboards replace the device\u2019s keyboard and make clients send a message with the predefined content. Inline keyboards are buttons attached to messages. Clicking on them causes the client to send a callback to the bot. In both scenarios the bot receives an update of a corresponding type and has to acknowledge the keayboard interaction for the client to work properly.

"},{"location":"tgbotapi/introduction/before-any-bot-project.html","title":"Before any bot project","text":"

There are several places you need to visit for starting work with any Telegram Bot framework on any language:

Anyway, the most important link is How do I create a bot? inside of Telegram Bot API

"},{"location":"tgbotapi/introduction/before-any-bot-project.html#next-steps","title":"Next steps","text":""},{"location":"tgbotapi/introduction/first-bot.html","title":"First bot","text":"

Examples info

A lot of examples with using of Telegram Bot API you can find in this github repository

"},{"location":"tgbotapi/introduction/first-bot.html#the-most-simple-bot","title":"The most simple bot","text":"

The most simple bot will just print information about itself. All source code you can find in this repository. Our interest here will be concentrated on the next example part:

suspend fun main(vararg args: String) {\n  val botToken = args.first()\n  val bot = telegramBot(botToken)\n  println(bot.getMe())\n}\n

So, let\u2019s get understanding, about what is going on:

  1. suspend fun main(vararg args: String):
    • suspend required for making of requests inside of this function. For more info you can open official documentation for coroutins. In fact, suspend fun main is the same that fun main() = runBlocking {} from examples
  2. val botToken = args.first(): here we are just getting the bot token from first arguments of command line
  3. val bot = telegramBot(botToken) : inside of bot will be RequestsExecutor object which will be used for all requests in any project with this library
  4. println(bot.getMe()): here happens calling of getMe extension

As a result, we will see in the command line something like

ExtendedBot(id=ChatId(chatId=123456789), username=Username(username=@first_test_ee17e8_bot), firstName=Your bot name, lastName=, canJoinGroups=false, canReadAllGroupMessages=false, supportsInlineQueries=false)\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html","title":"Including in your project","text":"

There are three projects:

TelegramBotAPI

Also, there is an aggregator-version tgbotapi, which will automatically include all projects above. It is most recommended version due to the fact that it is including all necessary tools around TelegramBotAPI Core, but it is optionally due to the possible restrictions on the result methods count (for android) or bundle size

Examples

You can find full examples info in this repository. In this repository there full codes which are working in normal situation. Currently, there is only one exception when these examples could work incorrectly: you are living in the location where Telegram Bot API is unavailable. For solving this problem you can read Proxy setup part

"},{"location":"tgbotapi/introduction/including-in-your-project.html#notice-about-repository","title":"Notice about repository","text":"

To use this library, you will need to include Maven Central repository in your project

"},{"location":"tgbotapi/introduction/including-in-your-project.html#buildgradle","title":"build.gradle","text":"
mavenCentral()\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#pomxml","title":"pom.xml","text":"
<repository>\n  <id>central</id>\n  <name>mavenCentral</name>\n  <url>https://repo1.maven.org/maven2</url>\n</repository>\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#dev-channel","title":"Dev channel","text":"

Besides, there is developer versions repo. To use it in your project, add the repo in repositories section:

Gradle
maven {\n    url \"https://git.inmo.dev/api/packages/InsanusMokrassar/maven\"\n}\n
Maven
<repository>\n  <id>dev.inmo</id>\n  <name>InmoDev</name>\n  <url>https://git.inmo.dev/api/packages/InsanusMokrassar/maven</url>\n</repository>\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#telegrambotapi","title":"TelegramBotAPI","text":"

As tgbotapi_version variable in next snippets will be used variable with next last published version:

"},{"location":"tgbotapi/introduction/including-in-your-project.html#buildgradle_1","title":"build.gradle","text":"
implementation \"dev.inmo:tgbotapi:$tgbotapi_version\"\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#pomxml_1","title":"pom.xml","text":"
<dependency>\n    <groupId>dev.inmo</groupId>\n    <artifactId>tgbotapi</artifactId>\n    <version>${tgbotapi_version}</version>\n</dependency>\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#telegrambotapi-core","title":"TelegramBotAPI Core","text":"

As tgbotapi_version variable in next snippets will be used variable with next last published version:

"},{"location":"tgbotapi/introduction/including-in-your-project.html#buildgradle_2","title":"build.gradle","text":"
implementation \"dev.inmo:tgbotapi.core:$tgbotapi_version\"\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#pomxml_2","title":"pom.xml","text":"
<dependency>\n    <groupId>dev.inmo</groupId>\n    <artifactId>tgbotapi.core</artifactId>\n    <version>${tgbotapi_version}</version>\n</dependency>\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#telegrambotapi-api-extensions","title":"TelegramBotAPI API Extensions","text":"

As tgbotapi_version variable in next snippets will be used variable with next last published version:

"},{"location":"tgbotapi/introduction/including-in-your-project.html#buildgradle_3","title":"build.gradle","text":"
implementation \"dev.inmo:tgbotapi.api:$tgbotapi_version\"\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#pomxml_3","title":"pom.xml","text":"
<dependency>\n    <groupId>dev.inmo</groupId>\n    <artifactId>tgbotapi.api</artifactId>\n    <version>${tgbotapi_version}</version>\n</dependency>\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#telegrambotapi-utils-extensions","title":"TelegramBotAPI Utils Extensions","text":"

As tgbotapi_version variable in next snippets will be used variable with next last published version:

"},{"location":"tgbotapi/introduction/including-in-your-project.html#buildgradle_4","title":"build.gradle","text":"
implementation \"dev.inmo:tgbotapi.utils:$tgbotapi_version\"\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#pomxml_4","title":"pom.xml","text":"
<dependency>\n    <groupId>dev.inmo</groupId>\n    <artifactId>tgbotapi.utils</artifactId>\n    <version>${tgbotapi_version}</version>\n</dependency>\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#next-steps","title":"Next steps","text":""},{"location":"tgbotapi/introduction/proxy-setup.html","title":"Proxy setup","text":"

In some locations Telegram Bots API urls will be unavailable. In this case all examples will just throw exception like:

Exception in thread \"main\" java.net.ConnectException: Connection refused\n    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)\n    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)\n    at io.ktor.network.sockets.SocketImpl.connect$ktor_network(SocketImpl.kt:36)\n    at io.ktor.network.sockets.SocketImpl$connect$1.invokeSuspend(SocketImpl.kt)\n    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)\n    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)\n    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)\n    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:738)\n    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)\n    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)\n\nProcess finished with exit code 1\n

There are several ways to solve this problem:

"},{"location":"tgbotapi/introduction/proxy-setup.html#using-ktor-client-built-in-proxy","title":"Using Ktor Client built-in proxy","text":"

First of all, you will need to use one more library:

build.gradle:

implementation \"io.ktor:ktor-client-okhttp:2.3.5\"\n

Dependency note

In the snippet above was used version 2.3.5 which is actual for TelegramBotAPI at the moment of filling this documentation (october 11 2023, TelegramBotAPI version 9.2.2) and you can update version of this dependency in case if it is outdated.

For configuring proxy for your bot inside your program, you can use next snippet:

val botToken = \"HERE MUST BE YOUR TOKEN\" // (1)\nval bot = telegramBot(botToken) { // (2)\n    client = HttpClient(OkHttp) { // (3)\n        engine { // (4)\n            config { // (5)\n                proxy( // (6)\n                    Proxy( // (7)\n                        Proxy.Type.SOCKS, // (8)\n                        InetSocketAddress(\"127.0.0.1\", 1080) // (9)\n                    )\n                )\n            }\n        }\n    }\n}\n
  1. Here we are just creating variable botToken
  2. Start creating bot
  3. Setting HttpClient of our bot. On the time of documentation filling, OkHttp is one of the engines in Ktor system which supports socks proxy. More you can read on Ktor site in subparts about engines and proxy
  4. Start setting up of HttpClient engine
  5. Start setting up of HttpClient engine configuration
  6. Start setting up of proxy
  7. Creating proxy info object
  8. Saying that it is Socks proxy
  9. Creating address. Note that \"127.0.0.1\" and 1080 are configurable parameters
"},{"location":"tgbotapi/introduction/proxy-setup.html#more-complex-and-flexible-variant","title":"More complex and flexible variant","text":"

You may try to use custom engine for ktor. For example:

// JVM\n// OkHttp engine\n// Socks5 proxy\n\nval bot = telegramBot(botToken) { // (1)\n    val proxyHost = \"your proxy host\" // (2)\n    val proxyPort = 1080 //your proxy port // (3)\n    val username = \"proxy username\" // (4)\n    val password = \"proxy password\" // (5)\n\n    val proxyAddr = InetSocketAddress(proxyHost, proxyPort) // (6)\n    val proxy = Proxy(Proxy.Type.SOCKS, proxyAddr) // (7)\n\n    val passwordAuthentication = PasswordAuthentication(\n        username,\n        password.toCharArray()\n    ) // (8)\n    Authenticator.setDefault(object : Authenticator() { // (9)\n        override fun getPasswordAuthentication(): PasswordAuthentication? { // (10)\n            return if (requestingHost.lowercase() == proxyHost.lowercase()) { // (11)\n                passwordAuthentication\n            } else {\n                null\n            }\n        }\n    })\n    this.client = HttpClient(OkHttp) { // (12)\n        engine { // (13)\n            config { // (14)\n                proxy(proxy) // (15)\n            }\n        }\n    }\n}\n
  1. Start creating telegram bot
  2. Proxy host
  3. Proxy port
  4. Username for authentication. It is optional in case your proxy do not need auth
  5. Password for authentication. It is optional in case your proxy do not need auth
  6. Creating of proxy address for Proxy
  7. Proxy address and type information
  8. Proxy authentication info. It is optional in case your proxy do not need auth
  9. Setting up of authenticator. It is optional in case your proxy do not need auth
  10. Overriding of method that will return authentication info
  11. In case when request has been sent to the proxy (common request) - using authentication
  12. Creating of HttpClient and start configure it
  13. Start setup engine
  14. Start setup engine config
  15. Setting up of proxy information
"},{"location":"tgbotapi/introduction/proxy-setup.html#next-steps","title":"Next steps","text":""},{"location":"tgbotapi/logic/api-extensions.html","title":"API Extensions","text":"

API extensions is a module which you may include in your project in addition to core part. In most cases this module will allow just use syntax like bot.getUpdates() instead of bot.execute(GetUpdates()), but there are several other things you will achieve with that syntax.

"},{"location":"tgbotapi/logic/api-extensions.html#bot-builder","title":"Bot builder","text":"

This functionality allow you to build bot in more unified and comfortable way than standard creating with telegramBot function

buildBot(\n    \"TOKEN\"\n) {\n  proxy = ProxyBuilder.socks(host = \"127.0.0.1\", port = 4001) // just an example, more info on https://ktor.io/docs/proxy.html\n  ktorClientConfig = {\n    // configuring of ktor client\n  }\n  ktorClientEngineFactory = {\n   // configuring of ktor client engine \n  }\n}\n
"},{"location":"tgbotapi/logic/api-extensions.html#downloading-of-files","title":"Downloading of files","text":"

In standard library requests there are no way to download some file retrieved in updates or after requests. You may use syntax like bot.downloadFile(file) where file is TelegramMediaFile from telegram, FileId or even PathedFile from GetFile request (sources).

"},{"location":"tgbotapi/logic/api-extensions.html#live-location","title":"Live location","text":"

By default, you should handle updates of Live location by your code. But with extension bot#startLiveLocation you may provide all necessary startup parameters and handle updates with just calling updateLocation for retrieved LiveLocationProvider.

"},{"location":"tgbotapi/logic/api-extensions.html#what-is-next","title":"What is next?","text":"

There are several things you may read next:

"},{"location":"tgbotapi/logic/behaviour-builder-with-fsm.html","title":"Behaviour Builder with FSM","text":"

Behaviour builder with FSM is based on the MicroUtils FSM. There are several important things in FSM:

StatesMachine have two methods:

The most based way to create StatesMachine and register StateHandlers looks like in the next snippet:

buildFSM<TrafficLightState> {\n    strictlyOn<SomeState> {\n        // state handling\n    }\n}.start(CoroutineScope(...)).join()\n

Full example

You may find full example of FSM usage in the tests of FSM in MicroUtils

So, you must do next steps before you will launch your bot with FSM:

"},{"location":"tgbotapi/logic/behaviour-builder-with-fsm.html#bot-with-fsm","title":"Bot with FSM","text":"

There are several extensions for TelegramBot to create your bot with FSM:

All of them will take as an callback some object with type CustomBehaviourContextReceiver and will looks like in the next snippet:

telegramBotWithBehaviourAndFSMAndStartLongPolling<YourStateType>(\"BOT_TOKEN\") {\n    // here you may use any operations from BehaviourBuilder\n    // here you may use any operations from BehaviourContextWithFSMBuilder like strictlyOn and others\n}\n
"},{"location":"tgbotapi/logic/behaviour-builder-with-fsm.html#examples","title":"Examples","text":""},{"location":"tgbotapi/logic/behaviour-builder.html","title":"Behaviour Builder","text":"

In the previous pages about updates handling and was mentioned that currently in the most cases you should use Flows. So, there is an improvement for that system which hide direct work with flows and allow you to create more declarative logic of your bot.

"},{"location":"tgbotapi/logic/behaviour-builder.html#main-parts-of-behaviour-builder","title":"Main parts of Behaviour Builder","text":"

There are several things you should know for better understanding of behaviour builder:

"},{"location":"tgbotapi/logic/behaviour-builder.html#initialization","title":"Initialization","text":"

As was said above, there is buildBehaviour function which allow you set up your bot logic. Let\u2019s see an example:

val bot = telegramBot(\"TOKEN\")\n\nbot.buildBehaviour {\n  onCommand(\"start\") { // creating of trigger\n    val message = it\n    val content = message.content\n\n    reply(message, \"Ok, send me one photo\") // send text message with replying on incoming message\n\n    val photoContent = waitPhoto().first() // waitPhoto will return List, so, get first element\n\n    val photo = downloadFile(photoContent) // ByteArray of photo\n\n    // some logic with saving of photos\n  }\n}\n
"},{"location":"tgbotapi/logic/behaviour-builder.html#filters","title":"Filters","text":"

In most cases there are opportunity to filter some of messages before starting of main logic. Let\u2019s look at this using the example above:

val bot = telegramBot(\"TOKEN\")\n\nbot.buildBehaviour {\n  onCommand(\n    \"start\",\n    initialFilter = {\n      it.content.textSources.size == 1 // make sure that user has sent /start without any additions\n    }\n  ) {\n    // ...\n  }\n}\n

OR

val bot = telegramBot(\"TOKEN\")\n\nbot.buildBehaviour {\n  onCommand(\n    \"start\",\n    requireOnlyCommandInMessage = true // it is default, but you can overwrite it with `requireOnlyCommandInMessage = false`\n  ) {\n    // ...\n  }\n}\n
"},{"location":"tgbotapi/logic/exceptions-handling.html","title":"Exceptions handling","text":"

Unfortunatelly, exceptions handling in this library is a bit difficult in some places, but that have at least two reasons: flexibility and usability.

"},{"location":"tgbotapi/logic/exceptions-handling.html#in-place-handling","title":"\u201cIn place\u201d handling","text":"

In case you know, where exceptions are happening, you may use several tools for exceptions catching:

"},{"location":"tgbotapi/logic/exceptions-handling.html#catching-with-result","title":"Catching with result","text":"

If you prefer to receive Result objects instead of some weird callbacks, you may use the next syntax:

safelyWithResult {\n    // do something\n}.onSuccess { // will be called if everything is right\n    // handle success\n}.onFailure { // will be called if something went wrong\n    // handle error\n    it.printStackTrace()\n}.getOrThrow() // will return value or throw exception\n
"},{"location":"tgbotapi/logic/exceptions-handling.html#catching-with-callback","title":"Catching with callback","text":"

Also there is more simple (in some cases) way to handle exceptions with callbacks:

safely(\n  {\n      // handle error\n      it.printStackTrace()\n      null // return value\n  }\n) {\n    // do something\n}\n
"},{"location":"tgbotapi/logic/exceptions-handling.html#bonus-different-types-of-handling","title":"Bonus: different types of handling","text":"

There are two types of handling:

"},{"location":"tgbotapi/logic/exceptions-handling.html#global-exceptions-handling","title":"Global exceptions handling","text":"

The most simple way to configure exceptions handling is to change CoroutineContext when you are creating your CoroutineScope for bot processing:

val bot = telegramBot(\"TOKEN\")\n\nbot.buildBehaviour (\n    scope = scope,\n    defaultExceptionsHandler = {\n        it.printStackTrace()\n    }\n) {\n    // ...\n}\n

OR

val bot = telegramBotWithBehaviour (\n    \"TOKEN\",\n    scope = scope,\n    defaultExceptionsHandler = {\n        it.printStackTrace()\n    }\n) {\n    // ...\n}\n

Here we have used ContextSafelyExceptionHandler class. It will pass default handling of exceptions and will call the block in most cases when something inside of your bot logic has thrown exception.

"},{"location":"tgbotapi/logic/files-handling.html","title":"Files handling","text":"

According to the documentation there are several ways to work with files:

"},{"location":"tgbotapi/logic/files-handling.html#files-receiving","title":"Files receiving","text":"

There are several cases you may need in your app to work with files:

"},{"location":"tgbotapi/logic/files-handling.html#where-to-get-file-id-or-url","title":"Where to get File id or url?","text":"

The most simple way to send some file is to get file id and send it. You may get file id from any message with media. For example, if you have received some Message, you may use asCommonMessage conversation to be able to get its content and then convert it to some content with media. Full code here:

val message: Message;\n\nval fileId = message.asCommonMessage() ?.withContent<MediaContent>() ?.content ?.media ?.fileId;\n

WAT? O.o

In the code above we get some message, safely converted it to CommonMessage with asCommonMessage, then safely took its content via withContent<MediaContent>() ?.content and then just get its media file id.

"},{"location":"tgbotapi/logic/files-handling.html#download-files","title":"Download files","text":"

There are three ways to download files:

"},{"location":"tgbotapi/logic/files-handling.html#downloading-with-api-extensions","title":"Downloading with API extensions","text":""},{"location":"tgbotapi/logic/files-handling.html#files-jvmandroid","title":"Files (JVM/Android)","text":"
val bot: TelegramBot;\nval fileId: FileId;\nval outputFile: File;\n\nbot.downloadFile(fileId, outputFile)\n

See downloadFile extension docs in the JVM tab to get more available options

There is also way with saving of data into temporal file. That will allow you to do with data whatever you want without high requirements to memory or network connection:

val bot: TelegramBot;\nval fileId: FileId;\n\nval tempFile: File = bot.downloadFileToTemp(fileId)\n

See downloadFileToTemp extension docs to get more available options

"},{"location":"tgbotapi/logic/files-handling.html#byte-read-channel","title":"Byte read channel","text":"
val bot: TelegramBot;\nval fileId: FileId;\n\nval bytes: ByteReadChannelAllocator = bot.downloadFileStream(fileId)\n

See downloadFileStream extension docs to get more available options

"},{"location":"tgbotapi/logic/files-handling.html#byte-read-channel-allocator","title":"Byte read channel allocator","text":"
val bot: TelegramBot;\nval fileId: FileId;\n\nval bytes: ByteReadChannelAllocator = bot.downloadFileStreamAllocator(fileId)\n

See downloadFileStreamAllocator extension docs to get more available options

"},{"location":"tgbotapi/logic/files-handling.html#byte-arrays","title":"Byte arrays","text":"
val bot: TelegramBot;\nval fileId: FileId;\n\nval bytes: ByteArray = bot.downloadFile(fileId)\n

See downloadFile extension docs to get more available options

"},{"location":"tgbotapi/logic/files-handling.html#low-level-or-how-does-it-work","title":"Low level or how does it work?","text":"

You may download file with streams or with downloading into the memory first. On low level you should do several things. They are presented in next snippet:

val bot: TelegramBot;\nval fileId: FileId;\n\nval pathedFile: PathedFile = bot.execute(GetFile(fileId))\n\nval downloadedBytes: ByteArray = bot.execute(DownloadFile(pathedFile.filePath))\n

In the snippet above we are getting file PathedFile by its FileId and use it to download file bytes into memory using DownloadFile request.

You may use almost the same way but with byte read channel allocator:

val bot: TelegramBot;\nval fileId: FileId;\n\nval pathedFile: PathedFile = bot.execute(GetFile(fileId))\n\nval channelAllocator: ByteReadChannelAllocator = bot.execute(DownloadFileStream(pathedFile.filePath))\n\nval byteReadChannel: ByteReadChannel = channelAllocator()\n

And then you may look into ByteReadChannel docs to get more info about what you can do with that.

Several useful links

"},{"location":"tgbotapi/logic/files-handling.html#files-sending","title":"Files sending","text":"

Of course, in most cases you must be sure that file have correct type.

"},{"location":"tgbotapi/logic/files-handling.html#fileid-and-fileurl","title":"FileId and FileUrl","text":"

It is the most simple way to send any media in Telegram, but this way have several restrictions:

"},{"location":"tgbotapi/logic/files-handling.html#sending-via-file","title":"Sending via file","text":"

JS Restrictions

Sending via file is accessible from all supported platforms, but there is small note about JS - due to restrictions of work with streams and stream-like data (JS have no native support of files streaming) on this platform all the files will be loaded inside of RAM before the sending to the telegram services.

Sending via file is available throw the MultipartFile. There are several wayt to get it:

In most cases, sending via files looks like in the next snippet:

val file: File;\n\nbot.sendDocument(chatId, file.asMultipartFile())\n
"},{"location":"tgbotapi/logic/low-level-work-with-bots.html","title":"Low-level work with bots","text":"

The base version of library was done a lot of time ago and just got several additions related to improvements, updates in Telegram Bot API or some requests from our community.

"},{"location":"tgbotapi/logic/low-level-work-with-bots.html#base-things","title":"Base things","text":"

There are several important things in context of this library:

So, in most cases all your request calls with simplified api of this library (like bot.getMe()) will looks like bot.execute(GetMe). Result of these calls is defined in type of any request (for example, for GetMe request the result type is ExtendedBot). As a result, you can avoid any extension api (like special API extensions) and use low level request with full controlling of the whole logic flow.

"},{"location":"tgbotapi/logic/low-level-work-with-bots.html#how-to-handle-updates","title":"How to handle updates","text":"

As was written above, it will require some request:

val updates = bot.execute(GetUpdates())\n

Result type of GetUpdates request is Update. You may find inheritors of this interface in Update kdocs.

"},{"location":"tgbotapi/logic/low-level-work-with-bots.html#what-is-next","title":"What is next?","text":"

As was said above, you may look into our API extensions in case you wish to use more high-level functions instead of bot.execute(SomeRequest()). Besides, it will be very useful to know more about updates retrieving.

"},{"location":"tgbotapi/logic/media-groups.html","title":"Media Groups","text":"

As you know, Telegram have the feature named Media Groups. Media groups have several differences with the common messages:

"},{"location":"tgbotapi/logic/media-groups.html#specific-of-media-groups-in-libraries","title":"Specific of media groups in libraries","text":"

Row updates

In tgbotapi there is no any additional handling of media groups by default and in case you will use simple bot.getUpdates, you will get the list of row updates and media groups will be included in this list as separated messages with MediaGroupPartContent. In that case you may use convertWithMediaGroupUpdates to be able to work with media groups as will be described below

In case you are using standard long polling (one of alternatives is telegramBotWithBehaviourAndLongPolling) or webhooks updates will be converted uner the hood and as a result, you will take media groups as a content in one message:

telegramBotWithBehaviourAndLongPolling(\n  \"token\"\n) {\n  onVisualGallery { // it: CommonMessage<MediaGroupContent<VisualMediaGroupPartContent>>\n    it.content // MediaGroupContent<VisualMediaGroupPartContent>\n    it.content.group // List<MediaGroupCollectionContent.PartWrapper<VisualMediaGroupPartContent>>\n    it.content.group.forEach { // it: MediaGroupCollectionContent.PartWrapper<VisualMediaGroupPartContent>\n      it.messageId // source message id for current media group part\n      it.sourceMessage // source message for current media group part\n      it.content // VisualMediaGroupPartContent\n      println(it.content) // will print current content part info\n    }\n  }\n}\n

KDocs:

In two words, in difference with row Telegram Bot API, you will take media groups in one message instead of messages list.

"},{"location":"tgbotapi/logic/types-conversations.html","title":"Types conversations","text":"

One of the most important topics in context of tgbotapi is types conversations. This library is very strong-typed and a lot of things are based on types hierarchy. Lets look into the hierarchy of classes for the Message in 0.35.8:

As you may see, it is a little bit complex and require several tools for types conversation.

"},{"location":"tgbotapi/logic/types-conversations.html#as","title":"As","text":"

as conversations will return new type in case if it is possible. For example, when you got Message, you may use asContentMessage conversation to get message with content:

val message: Message;\nprintln(message.asContentMessage() ?.content)\n

This code will print null in case when message is not ContentMessage, and content when is.

"},{"location":"tgbotapi/logic/types-conversations.html#require","title":"Require","text":"

require works like as, but instead of returning nullable type, it will always return object with required type OR throw ClassCastException:

val message: Message;\nprintln(message.requireContentMessage().content)\n

This code will throw exception when message is not ContentMessage and print content when is.

"},{"location":"tgbotapi/logic/types-conversations.html#when","title":"When","text":"

when extensions will call passed block when type is correct. For example:

val message: Message;\nmessage.whenContentMessage {\n    println(it.content)\n}\n

Code placed above will print content when message is ContentMessage and do nothing when not

"},{"location":"tgbotapi/logic/updates-with-flows.html","title":"Updates with flows","text":"

Of course, in most cases here we will look up the way of using utils extnsions, but you may read deeper about updates retrieving here.

"},{"location":"tgbotapi/logic/updates-with-flows.html#phylosophy-of-flow-updates-retrieving","title":"Phylosophy of Flow updates retrieving","text":"

In most updates retrieving processes there are two components: UpdatesFiler and its inheritor FlowsUpdatesFilter. It is assumed, that you will do several things in your app to handle updates:

Let\u2019s look how it works with the factory above:

// Step 1 - create filter\nval filter = flowsUpdatesFilter {\n  // Step 2 - set up handling. In this case we will print any message from group or user in console\n  messageFlow.onEach {\n    println(it)\n  }.launchIn(someCoroutineScope)\n}\n\n// Step 3 - passing updates to filter\nbot.getUpdates().forEach {\n  filter.asUpdatesReceiver(it)\n}\n
"},{"location":"tgbotapi/logic/updates-with-flows.html#long-polling","title":"Long polling","text":"

Some example with long polling has been described above. But it is more useful to use some factories for it. In this page we will look for simple variant with TelegramBot#longPolling. So, with this function, your handling of updates will looks like:

val bot = telegramBot(\"TOKEN\")\n\nbot.longPolling {\n  messageFlow.onEach {\n    println(it)\n  }.launchIn(someCoroutineScope)\n}.join()\n

This example looks like the example above with three steps, but there are several important things here:

"},{"location":"tgbotapi/logic/updates-with-flows.html#results-and-what-is-next","title":"Results and What is next?","text":"

As a result you can start listen updates and react on it. Next recommended articles:

"},{"location":"tgbotapi/updates/heroku.html","title":"Heroku","text":"

Preview reading

It is recommended to visit our pages about UpdatesFilters and Webhooks to have more clear understanding about what is happening in this examples page

Heroku is a popular place for bots hosting. In common case you will need to configure webhooks for your server to include getting updates without problems. There are several things related to heroku you should know:

Server configuration alternatives

Here will be presented variants of configuration of webhooks and starting server. You always able to set webhook manualy, create your own ktor server and include webhooks handling in it or create and start server with only webhooks handling. More info you can get on page Webhooks

"},{"location":"tgbotapi/updates/heroku.html#short-example-with-behaviour-builder","title":"Short example with Behaviour Builder","text":"
suspend fun main {\n    // This subroute will be used as random webhook subroute to improve security according to the recommendations of Telegram\n    val subroute = uuid4().toString()\n    // Input/Output coroutines scope more info here: https://kotlinlang.org/docs/coroutines-guide.html\n    val scope = CoroutineScope(Dispatchers.IO)\n    // Here will be automatically created bot and available inside of lambda where you will setup your bot behaviour\n    telegramBotWithBehaviour(\n        // Pass TOKEN inside of your application environment variables\n        System.getenv(\"TOKEN\"),\n        scope = scope\n    ) {\n        // Set up webhooks and start to listen them\n        setWebhookInfoAndStartListenWebhooks(\n            // Automatic env which will be passed by heroku to the app\n            System.getenv(\"PORT\").toInt(),\n            // Server engine. More info here: https://ktor.io/docs/engines.html\n            Tomcat,\n            // Pass URL environment variable via settings of application. It must looks like https://<app name>.herokuapp.com\n            SetWebhook(\"${System.getenv(\"URL\").removeSuffix(\"/\")}/$subroute\"),\n            // Just callback which will be called when exceptions will happen inside of webhooks\n            {\n                it.printStackTrace()\n            },\n            // Set up listen requests from outside\n            \"0.0.0.0\",\n            // Set up subroute to listen webhooks to\n            subroute,\n            // BehaviourContext is the CoroutineScope and it is recommended to pass it inside of webhooks server\n            scope = this,\n            // BehaviourContext is the FlowsUpdatesFilter and it is recommended to pass its asUpdateReceiver as a block to retrieve all the updates\n            block = asUpdateReceiver\n        )\n        // Test reaction on each command with reply and text `Got it`\n        onUnhandledCommand {\n            reply(it, \"Got it\")\n        }\n    }\n    // Just potentially infinite await of bot completion\n    scope.coroutineContext.job.join()\n}\n
"},{"location":"tgbotapi/updates/heroku.html#configuration-example-without-behaviour-builder","title":"Configuration example without Behaviour Builder","text":"
// This subroute will be used as random webhook subroute to improve security according to the recommendations of Telegram\nval subroute = uuid4().toString()\nval bot = telegramBot(TOKEN)\nval scope = CoroutineScope(Dispatchers.Default)\n\nval filter = flowsUpdatesFilter {\n  messageFlow.onEach {\n    println(it) // will be printed \n  }.launchIn(scope)\n}\n\nval subroute = UUID.randomUUID().toString() // It will be used as subpath for security target as recommended by https://core.telegram.org/bots/api#setwebhook\n\nval server = bot.setWebhookInfoAndStartListenWebhooks(\n  // Automatic env which will be passed by heroku to the app\n  System.getenv(\"PORT\").toInt(),\n  // Server engine. More info here: https://ktor.io/docs/engines.html\n  Tomcat,\n  // Pass URL environment variable via settings of application. It must looks like https://<app name>.herokuapp.com\n  SetWebhook(\"${System.getenv(\"URL\").removeSuffix(\"/\")}/$subroute\"),\n  // Just callback which will be called when exceptions will happen inside of webhooks\n  {\n    it.printStackTrace()\n  },\n  // Set up listen requests from outside\n  \"0.0.0.0\",\n  // Set up subroute to listen webhooks to\n  subroute,\n  scope = scope,\n  block = filter.asUpdateReceiver\n)\n\nserver.environment.connectors.forEach {\n  println(it)\n}\nserver.start(false)\n
"},{"location":"tgbotapi/updates/long-polling.html","title":"Long polling","text":"

Long polling is a technology of getting updates for cases you do not have some dedicated server or you have no opportunity to receive updates via webhooks. More about this you can read in wiki.

"},{"location":"tgbotapi/updates/long-polling.html#related-topics","title":"Related topics","text":""},{"location":"tgbotapi/updates/long-polling.html#long-polling-in-this-library","title":"Long polling in this library","text":"

There are a lot of ways to include work with long polling:

"},{"location":"tgbotapi/updates/long-polling.html#longpolling","title":"longPolling","text":"

longPolling is a simple way to start getting updates and work with bot:

val bot = telegramBot(token)\nbot.longPolling(\n  textMessages().subscribe(scope) { // here \"scope\" is a CoroutineScope\n    println(it) // will be printed each update from chats with messages\n  }\n)\n
"},{"location":"tgbotapi/updates/long-polling.html#startgettingofupdatesbylongpolling","title":"startGettingOfUpdatesByLongPolling","text":"

The main aim of startGettingOfUpdatesByLongPolling extension was to provide more simple way to get updates in automatic mode:

val bot = telegramBot(token)\nbot.startGettingOfUpdatesByLongPolling(\n  {\n    println(it) // will be printed each update from chats with messages\n  }\n)\n

The other way is to use the most basic startGettingOfUpdatesByLongPolling extension:

val bot = telegramBot(token)\nbot.startGettingOfUpdatesByLongPolling {\n  println(it) // will be printed each update\n}\n
"},{"location":"tgbotapi/updates/long-polling.html#see-also","title":"See also","text":""},{"location":"tgbotapi/updates/updates-filters.html","title":"Updates filters","text":"

Due to the fact, that anyway you will get updates in one format (Update objects), some time ago was solved to create one point of updates filters for more usefull way of updates handling

"},{"location":"tgbotapi/updates/updates-filters.html#updatesfilter","title":"UpdatesFilter","text":"

UpdatesFilter currently have two properties:

Anyway, this filter can\u2019t work with updates by itself. For retrieving updates you should pass this filter to some of getting updates functions (long polling or webhooks).

"},{"location":"tgbotapi/updates/updates-filters.html#simpleupdatesfilter","title":"SimpleUpdatesFilter","text":"

SimpleUpdatesFilter is a simple variant of filters. It have a lot of UpdateReceiver properties which can be set up on creating of this object. For example, if you wish to get messages from chats (but not from channels), you can use next snippet:

SimpleUpdatesFilter {\n  println(it)\n}\n
"},{"location":"tgbotapi/updates/updates-filters.html#flowsupdatesfilter","title":"FlowsUpdatesFilter","text":"

A little bit more modern way is to use FlowsUpdatesFilter. It is very powerfull API of Kotlin Coroutines Flows, built-in support of additional extensions for FlowsUpdatesFilter and Flow<...> receivers and opportunity to split one filter for as much receivers as you want. Filter creating example:

val scope = CoroutineScope(Dispatchers.Default)\nflowsUpdatesFilter {\n  messageFlow.onEach {\n    println(it)\n  }.launchIn(scope)\n}\n
"},{"location":"tgbotapi/updates/updates-filters.html#combining-of-flows","title":"Combining of flows","text":"

In cases you need not separate logic for handling of messages from channels and chats there are three ways to combine different flows into one:

"},{"location":"tgbotapi/updates/updates-filters.html#types-filtering","title":"Types filtering","text":"

FlowsUpdatesFilter have a lot of extensions for messages types filtering:

flowsUpdatesFilter {\n  textMessages(scope).onEach {\n    println(it) // will be printed each message from channels and chats both with content only `TextContent`\n  }.launchIn(scope)\n}\n

The same things were created for media groups:

flowsUpdatesFilter {\n  mediaGroupMessages(scope).onEach {\n    println(it) // will be printed each media group messages list from both channels and chats without filtering of content\n  }.launchIn(scope)\n\n  mediaGroupPhotosMessages(scope).onEach {\n    println(it) // will be printed each media group messages list from both channels and chats with PhotoContent only\n  }.launchIn(scope)\n\n  mediaGroupVideosMessages(scope).onEach {\n    println(it) // will be printed each media group messages list from both channels and chats with VideoContent only\n  }.launchIn(scope)\n}\n

Besides, there is an opportunity to avoid separation on media groups and common messages and receive photos and videos content in one flow:

flowsUpdatesFilter {\n  sentMessagesWithMediaGroups(scope).onEach {\n    println(it) // will be printed each message including each separated media group message from both channels and chats without filtering of content\n  }.launchIn(scope)\n\n  photoMessagesWithMediaGroups(scope).onEach {\n    println(it) // will be printed each message including each separated media group message from both channels and chats with PhotoContent only\n  }.launchIn(scope)\n\n  videoMessagesWithMediaGroups(scope).onEach {\n    println(it) // will be printed each message including each separated media group message from both channels and chats with VideoContent only\n  }.launchIn(scope)\n}\n
"},{"location":"tgbotapi/updates/updates-filters.html#see-also","title":"See also","text":""},{"location":"tgbotapi/updates/webhooks.html","title":"Webhooks","text":"

In telegram bot API there is an opportunity to get updates via webhooks. In this case you will be able to retrieve updates without making additional requests. Most of currently available methods for webhooks are working on ktor server for JVM. Currently, next ways are available for using for webhooks:

"},{"location":"tgbotapi/updates/webhooks.html#setwebhookinfoandstartlistenwebhooks","title":"setWebhookInfoAndStartListenWebhooks","text":"

It is the most common way to set updates webhooks and start listening of them. Example:

val bot = telegramBot(TOKEN)\n\nval filter = flowsUpdatesFilter {\n  // ...\n}\n\nbot.setWebhookInfoAndStartListenWebhooks(\n  8080, // listening port. It is required for cases when your server hidden by some proxy or other system like Heroku\n  CIO, // default ktor server engine. It is recommended to replace it with something like `Netty`. More info about engines here: https://ktor.io/servers/configuration.html\n  SetWebhook(\n    \"address.com/webhook_route\",\n    File(\"/path/to/certificate\").toInputFile(), // certificate file. More info here: https://core.telegram.org/bots/webhooks#a-certificate-where-do-i-get-one-and-how\n    40, // max allowed updates, by default is null\n    filter.allowedUpdates\n  ),\n  {\n    it.printStackTrace() // optional handling of exceptions\n  },\n  \"0.0.0.0\", // listening host which will be used to bind by server\n  \"subroute\", // Optional subroute, if null - will listen root of address\n  WebhookPrivateKeyConfig( // optional config of private key. It will be installed in server to use TLS with custom certificate. More info here: https://core.telegram.org/bots/webhooks#a-certificate-where-do-i-get-one-and-how\n    \"/path/to/keystore.jks\",\n    \"KeystorePassword\",\n    \"Keystore key alias name\",\n    \"KeystoreAliasPassword\"\n  ),\n  scope, // Kotlin coroutine scope for internal transforming of media groups\n  filter.asUpdateReceiver\n)\n

If you will use previous example, ktor server will bind and listen url 0.0.0.0:8080/subroute and telegram will send requests to address address.com/webhook_route with custom certificate. Alternative variant will use the other SetWebhook request variant:

SetWebhook(\n  \"address.com/webhook_route\",\n  \"some_file_bot_id\".toInputFile(),\n  40, // max allowed updates, by default is null\n  filter.allowedUpdates\n)\n

As a result, request SetWebhook will be executed and after this server will start its working and handling of updates.

"},{"location":"tgbotapi/updates/webhooks.html#startlistenwebhooks","title":"startListenWebhooks","text":"

This function is working almost exactly like previous example, but this one will not set up webhook info in telegram:

val filter = flowsUpdatesFilter {\n  // ...\n}\n\nstartListenWebhooks(\n  8080, // listening port. It is required for cases when your server hidden by some proxy or other system like Heroku\n  CIO, // default ktor server engine. It is recommended to replace it with something like `Netty`. More info about engines here: https://ktor.io/servers/configuration.html\n  {\n    it.printStackTrace() // optional handling of exceptions\n  },\n  \"0.0.0.0\", // listening host which will be used to bind by server\n  \"subroute\", // Optional subroute, if null - will listen root of address\n  WebhookPrivateKeyConfig( // optional config of private key. It will be installed in server to use TLS with custom certificate. More info here: https://core.telegram.org/bots/webhooks#a-certificate-where-do-i-get-one-and-how\n    \"/path/to/keystore.jks\",\n    \"KeystorePassword\",\n    \"Keystore key alias name\",\n    \"KeystoreAliasPassword\"\n  ),\n  scope, // Kotlin coroutine scope for internal transforming of media groups\n  filter.asUpdateReceiver\n)\n

The result will be the same as in previous example: server will start its working and handling of updates on 0.0.0.0:8080/subroute. The difference here is that in case if this bot must not answer or send some requiests - it will not be necessary to create bot for receiving of updates.

"},{"location":"tgbotapi/updates/webhooks.html#extensions-includewebhookhandlinginroute-and-includewebhookhandlinginroutewithflows","title":"Extensions includeWebhookHandlingInRoute and includeWebhookHandlingInRouteWithFlows","text":"

For these extensions you will need to start your server manualy. In common case it will look like:

val scope = CoroutineScope(Dispatchers.Default)\n\nval filter = flowsUpdatesFilter {\n  // ...\n}\n\nval environment = applicationEngineEnvironment {\n  module {\n    routing {\n      includeWebhookHandlingInRoute(\n        scope,\n        {\n          it.printStackTrace()\n        },\n        filter.asUpdateReceiver\n      )\n    }\n  }\n  connector {\n    host = \"0.0.0.0\"\n    port = 8080\n  }\n}\n\nembeddedServer(CIO, environment).start(true) // will start server and wait its stoping\n

In the example above server will started and binded for listening on 0.0.0.0:8080.

"},{"location":"tgbotapi/updates/webhooks.html#see-also","title":"See also","text":""}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"index.html","title":"Insanus Mokrassar libraries home","text":"

Hello :) It is my libraries docs place and I glad to welcome you here. I hope, this documentation place will help you.

"},{"location":"index.html#projects","title":"Projects","text":"Common and independent TelegramBotAPI Plagubot"},{"location":"index.html#dependencies-graph","title":"Dependencies graph:","text":"%%{init: {\"flowchart\": {\"defaultRenderer\": \"elk\"}} }%% flowchart TB KSLog[KSLog] MicroUtils[MicroUtils] TelegramBotAPI[TelegramBotAPI] TelegramBotAPI-examples[TelegramBotAPI-examples ] PlaguBot[PlaguBot] TelegramBotAPILibraries[TelegramBotAPILibraries] PlaguBotPlugins[PlaguBotPlugins] PlaguBotExample[PlaguBotExample] BooruGrabberTelegramBot[BooruGrabberTelegramBot] SauceNaoTelegramBot[SauceNaoTelegramBot] PlaguPoster[PlaguPoster] PlaguBotSuggestionsBot[PlaguBotSuggestionsBot] TelegramBotTutorial[TelegramBotTutorial] Krontab[Krontab] KJSUiKit[KJSUiKit] SauceNaoAPI[SauceNaoAPI] Navigation[Navigation] TelegramBotAPI-bot_template[TelegramBotAPI-bot_template] PlaguBotPluginTemplate[PlaguBotPluginTemplate] PlaguBotBotTemplate[PlaguBotBotTemplate] MicroUtils --> KSLog TelegramBotAPI --> MicroUtils TelegramBotAPI-examples --> TelegramBotAPI PlaguBot --> TelegramBotAPI TelegramBotAPILibraries --> PlaguBot PlaguBotPlugins --> TelegramBotAPILibraries PlaguBotExample --> PlaguBotPlugins BooruGrabberTelegramBot --> TelegramBotAPI BooruGrabberTelegramBot --> Krontab SauceNaoTelegramBot --> TelegramBotAPI SauceNaoTelegramBot --> SauceNaoAPI TelegramBotTutorial --> PlaguBotPlugins PlaguBotSuggestionsBot --> PlaguBotPlugins PlaguPoster --> PlaguBotPlugins PlaguPoster --> Krontab SauceNaoAPI --> MicroUtils Navigation --> MicroUtils TelegramBotAPI-bot_template -.- TelegramBotAPI PlaguBotPluginTemplate -.- PlaguBot PlaguBotBotTemplate -.- PlaguBot"},{"location":"krontab/index.html","title":"krontab","text":"

Library was created to give opportunity to launch some things from time to time according to some schedule in runtime of applications.

"},{"location":"krontab/index.html#how-to-use","title":"How to use","text":"

Here you may find the builder for Krontab templates creation.

There are several ways to configure and use this library:

Anyway, to start some action from time to time you will need to use one of extensions/functions:

val kronScheduler = /* creating of KronScheduler instance */;\n\nkronScheduler.doWhile {\n    // some action\n    true // true - repeat on next time\n}\n
"},{"location":"krontab/index.html#including-in-project","title":"Including in project","text":"

If you want to include krontab in your project, just add next line to your dependencies part:

implementation \"dev.inmo:krontab:$krontab_version\"\n

Next version is the latest currently for the library:

For old version of Gradle, instead of implementation word developers must use compile.

"},{"location":"krontab/index.html#config-from-string","title":"Config from string","text":"

Developers can use more simple way to configure repeat times is string. String configuring like a crontab, but with a little bit different meanings:

/--------------- Seconds\n| /------------- Minutes\n| | /----------- Hours\n| | | /--------- Days of months\n| | | | /------- Months\n| | | | | /----- (optional) Year\n| | | | | | /--- (optional) Timezone offset\n| | | | | | |  / (optional) Week days\n* * * * * * 0o *w\n

It is different with original crontab syntax for the reason, that expected that in practice developers will use seconds and minutes with more probability than months (for example) or even years. In fact, developers will use something like:

doWhile(\"/5 * * * *\") {\n    println(\"Called\")\n    true // true - repeat on next time\n}\n

Another version:

doInfinity(\"/5 * * * *\") {\n    println(\"Called\")\n}\n

Both of examples will print Called message every five seconds.

"},{"location":"krontab/index.html#config-via-builder","title":"Config via builder","text":"

Also, this library currently supports DSL for creating the same goals:

val kronScheduler = buildSchedule {\n    seconds {\n        from (0) every 5\n    }\n}\nkronScheduler.doWhile {\n    println(\"Called\")\n    true // true - repeat on next time\n}\n

Or

val kronScheduler = buildSchedule {\n    seconds {\n        0 every 5\n    }\n}\nkronScheduler.doWhile {\n    println(\"Called\")\n    true // true - repeat on next time\n}\n

Or

val kronScheduler = buildSchedule {\n    seconds {\n        0 every 5\n    }\n}\nkronScheduler.doInfinity {\n    println(\"Called\")\n}\n

All of these examples will do the same things: print Called message every five seconds.

"},{"location":"krontab/index.html#do-functions","title":"do* functions","text":"

With regular doOnce/doWhile/doInfinity there are two types of their variations: local and timezoned. Local variations (doOnceLocal/doWhileLocal/doInfinityLocal) will pass DateTime as an argument into the block:

doInfinityLocal(\"/5 * * * *\") {\n    println(it) // will print current date time\n}\n

Timezoned variations (doOnceTz/doWhileTz/doInfinityTz) will do the same thing but pass as an argument DateTimeTz:

doInfinityTz(\"/5 * * * * 0o\") {\n    println(it) // will print current date time in UTC\n}\n

It is useful in cases when you need to get the time of calling and avoid extra calls to system time.

"},{"location":"krontab/index.html#helpful-table-for","title":"Helpful table for","text":"No args Local DateTime Local DateTimeTz with offset of KronScheduler Call only near time doOnce doOnceLocal doOnceTz Call while condition is true doWhile doWhileLocal doWhileTz Work infinity* doInfinity doInfinityLocal doInfinityTz

*Here there is an important notice, that Work infinity is not exactly infinity. Actually, that means that do while coroutine is alive and in fact executing will be stopped when coroutine became cancelled.

"},{"location":"krontab/index.html#kronscheduler-as-a-flow","title":"KronScheduler as a Flow","text":"

Any KronScheduler can be converted to a Flow<DateTime> using extension asFlow:

val kronScheduler = buildSchedule {\n    seconds {\n        0 every 1\n    }\n}\n\nval flow = kronScheduler.asFlow()\n

So, in this case any operations related to flow are available, and it is expected that they will work correctly. For example, it is possible to use this flow with takeWhile:

flow.takeWhile {\n    condition()\n}.collect {\n    action()\n}\n
"},{"location":"krontab/index.html#offsets","title":"Offsets","text":"

Offsets in this library works via passing parameter ending with o in any place after month config. Currently, there is only one format supported for offsets: minutes of offsets. To use time zones you will need to call next method with DateTimeTz argument or nextTimeZoned method with any KronScheduler instance, but in case if this scheduler is not instance of KronSchedulerTz it will work like you passed just DateTime.

Besides, in case you wish to use time zones explicitly, you will need to get KronSchedulerTz. It is possible by:

"},{"location":"krontab/index.html#note-about-week-days","title":"Note about week days","text":"

Unlike original CRON, here week days:

"},{"location":"krontab/describing/krontabscheduler.html","title":"KrontabScheduler","text":"

KronScheduler is the simple interface with only one function next. This function optionally get as a parameter DateTime which will be used as start point for the calculation of next trigger time. This function will return the next DateTime when something must happen.

"},{"location":"krontab/describing/krontabscheduler.html#default-realisation","title":"Default realisation","text":"

Default realisation (CronDateTimeScheduler) can be created using several ways:

In the examples below the result of created scheduler will be the same.

"},{"location":"krontab/describing/krontabscheduler.html#crontab-like-way","title":"Crontab-like way","text":"

Crontab-like syntax

See String format for more info about the crontab-line syntax

This way will be very useful for cases when you need to configure something via external configuration (from file on startup or via some parameter from requests, for example):

val schedule = \"5 * * * *\"\nval scheduler = buildSchedule(schedule)\n\nscheduler.asFlow().onEach {\n  // this block will be called every minute at 5 seconds\n}.launchIn(someCoroutineScope)\n
"},{"location":"krontab/describing/krontabscheduler.html#lambda-way","title":"Lambda way","text":"

In case of usage builder (lets call it lambda way), you will be able to configure scheduler in more type-safe way:

val scheduler = buildSchedule {\n  seconds {\n    at(5)\n  }\n}\n\nscheduler.asFlow().onEach {\n  // this block will be called every minute at 5 seconds\n}.launchIn(someCoroutineScope)\n
"},{"location":"krontab/describing/krontabscheduler.html#custom-scheduler","title":"Custom scheduler","text":"

You are always able to use your own realisation of scheduler. For example:

class RandomScheduler : KronScheduler {\n  override suspend fun next(relatively: DateTime): DateTime {\n    return relatively + DateTimeSpan(seconds = Random.nextInt() % 60)\n  }\n}\n

In the example above we have created RandomScheduler, which will return random next time in range 0-60 seconds since relatively argument.

"},{"location":"krontab/describing/string-format.html","title":"String format","text":"

As in crontab util, this library have almost the same format of string:

Seconds Minutes Hours Days of months Months Years Timezone Offset Week days Milliseconds Range 0..59 0..59 0..23 0..30 0..11 Any Int Any Int 0..6 0..999 Suffix - - - - - - o w ms Optional \u274c \u274c \u274c \u274c \u274c \u2705 \u2705 \u2705 \u2705 Full syntax support \u2705 \u2705 \u2705 \u2705 \u2705 \u2705 \u274c \u2705 \u2705 Position 0 1 2 3 4 Any after months Any after months Any after months Any after months Examples 0, */15, 30 0, */15, 30 0, */15, 22 0, */15, 30 0, */5, 11 0, */15, 30 60o (UTC+1) 0w, */2w, 4w 0ms, */150ms, 300ms

Example with almost same description:

/-------------------- (0-59) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Seconds\n| /------------------ (0-59) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Minutes\n| | /---------------- (0-23) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Hours\n| | | /-------------- (0-30) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Days of months\n| | | | /------------ (0-11) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Months\n| | | | | /---------- (optional, any int) Year\n| | | | | | /-------- (optional) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Timezone offset\n| | | | | | |  /----- (optional, 0-6) \u00b7\u00b7\u00b7 Week days\n| | | | | | |  |  /-- (optional, 0-999) \u00b7 Milliseconds (0 by default)\n* * * * * * 0o *w 0ms\n

Years, timezone, week days and milliseconds are optional settings. Next snippets are equal:

*/15 * * * *\n*/15 * * * * * // with year\n*/15 * * * * * 0ms // with year and milliseconds\n
"},{"location":"krontab/describing/string-format.html#supported-syntax","title":"Supported syntax","text":"

Currently the library support next syntax for date/time elements:

"},{"location":"krontab/describing/string-format.html#ranges","title":"Ranges","text":"

Ranges are working like common rangeTo (or ..) in kotlin:

0-5 * * * *\n

In the example above scheduler will trigger every second from the beginning of the minute up to fifth second of minute.

"},{"location":"krontab/describing/string-format.html#startstep","title":"Start/Step","text":"

Start/step is a little bit more complicated syntax. It means start from the first element, repeat triggering every second element. Examples:

5/15 * * * *\n

Means that each minute starting from fifth second it will repeat triggering every fifteenth second: 5, 20, 35, 50.

"},{"location":"krontab/describing/string-format.html#every","title":"Every","text":"

Every is more simple syntax and could be explained as a shortcut for 0/{int}. Example:

*/15 * * * *\n

Means that each minute it will repeat triggering every fifteenth second: 0, 15, 30, 45.

"},{"location":"krontab/describing/string-format.html#just-at-the-time","title":"Just at the time","text":"

The most simple syntax. It means, that scheduler will call triggering every time when element was reached:

15 * * * *\n

Means that each minute scheduler will call triggering at the fifteenth second.

"},{"location":"krontab/describing/string-format.html#listing","title":"Listing","text":"

All the previous elements can be combined with listing. Lets just see several examples:

0,10 * * * *\n

Will trigger every minute at the 0 and 10 seconds (see Just at the time)

0-5,10 * * * *\n

Will trigger every minute from 0 to 5 seconds and at the 10 seconds (see Ranges)

"},{"location":"krontab/describing/string-format.html#examples","title":"Examples","text":""},{"location":"krontab/introduction/faq.html","title":"FAQ","text":""},{"location":"krontab/introduction/faq.html#how-oftern-new-versions-are-releasing","title":"How oftern new versions are releasing?","text":"

Not very often. It depends on libraries (coroutines, korlibs/klock) updates and on some new awesome, but lightweight, features coming.

"},{"location":"krontab/introduction/faq.html#where-this-library-could-be-useful","title":"Where this library could be useful?","text":"

First of all, this library will be useful for long uptime applications which have some tasks to do from time to time.

"},{"location":"krontab/introduction/faq.html#how-to-use-crontab-like-syntax","title":"How to use crontab-like syntax?","text":"

In two words, you should call buildSchedule or createSimpleScheduler:

buildSchedule(\"5 * * * *\").asFlow().collect { /* do something */ }\n

You can read more about syntax in String format section.

"},{"location":"krontab/introduction/how-to-use.html","title":"How to use","text":""},{"location":"krontab/introduction/how-to-use.html#previous-pages","title":"Previous pages","text":""},{"location":"krontab/introduction/how-to-use.html#buildschedule","title":"buildSchedule","text":"

Custom KronScheduler

You are always may create your own scheduler. In this section will be presented different ways and examples around standard CronDateTimeScheduler builders buildSchedule. You can read about schedulers in KrontabScheduler

Currently, buildSchedule is the recommended start point for every scheduler. Usually, it is look like:

val scheduler = buildSchedule(\"5 * * * *\")\n

Or:

val scheduler = buildSchedule {\n  seconds {\n    at(5)\n  }\n}\n

On the top of any KronScheduler currently there are several groups of extensions:

"},{"location":"krontab/introduction/how-to-use.html#executes","title":"Executes","text":"

All executes are look like do.... All executes are described below:

"},{"location":"krontab/introduction/how-to-use.html#shortcuts","title":"Shortcuts","text":"

Shortcuts are the constants that are initializing in a lazy way to provide preset KronSchedulers. For more info about KrontabScheduler you can read its own page.

"},{"location":"krontab/introduction/how-to-use.html#flows","title":"Flows","text":"

Here currently there is only one extension for KronScheduler: KronScheduler#asFlow. As a result you will get Flow<DateTime> (in fact SchedulerFlow) which will trigger next emit on each not null next DateTime

"},{"location":"krontab/introduction/including-in-project.html","title":"Including in project","text":"

In two words, you must add dependency dev.inmo:krontab:$krontab_version to your project. The latest version presented by next badge:

"},{"location":"krontab/introduction/including-in-project.html#notice-about-repository","title":"Notice about repository","text":"

To use this library, you will need to include MavenCentral repository in you project

"},{"location":"krontab/introduction/including-in-project.html#buildgradle","title":"build.gradle","text":"
mavenCentral()\n
"},{"location":"krontab/introduction/including-in-project.html#dependencies","title":"Dependencies","text":"

Next snippets must be placed into your dependencies part of build.gradle (for gradle) or pom.xml (for maven).

"},{"location":"krontab/introduction/including-in-project.html#gradle","title":"Gradle","text":"
implementation \"dev.inmo:krontab:$krontab_version\"\n
"},{"location":"krontab/introduction/including-in-project.html#maven","title":"Maven","text":"
<dependency>\n    <groupId>dev.inmo</groupId>\n    <artifactId>krontab</artifactId>\n    <version>${krontab_version}</version>\n</dependency>\n
"},{"location":"kslog/index.html","title":"KSLog","text":"

It is simple and easy-to-use tool for logging on the most popular platforms in Kotlin Multiplatform:

By default, KSLog is using built-in tools for logging on each supported platform:

But you always may create your logger and customize as you wish:

KSLog.default = KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->\n    // do your logging\n}\n

This library also supports native targets in experimental mode. By default, all native targets will use simple printing in the console

"},{"location":"kslog/index.html#how-to-use","title":"How to use","text":""},{"location":"kslog/index.html#fast-travel","title":"Fast-travel","text":"

Just use some boring extensions like:

KSLog.i(\"Some message\")\n// OR\nKSLog.i(\"Some tag\", \"Some message\")\n// OR\nKSLog.i(\"Some tag\", \"Some message\", IllegalArgumentException(\"So, that is exception :)\"))\n// OR\nKSLog.i(\"Some optional tag\", Exception(\"Optional\")) { \"Lazy inited message\" }\n// OR\nKSLog.iS(\"Some optional tag\", Exception(\"Optional\")) { \"Lazy inited message for suspendable calculation of text\" }\n// OR EVEN\nKSLog.l(LogLevel.INFO, \"Some tag\", \"Some message\", IllegalArgumentException(\"So, that is exception :)\"))\n// OR\nKSLog.l(LogLevel.INFO, \"Some optional tag\", IllegalArgumentException(\"So, that is exception :)\")) { \"And lazily inited message\" }\n
"},{"location":"kslog/index.html#a-little-bit-deeper","title":"A little bit deeper","text":"

There are several important \u201cterms\u201d in context of this library:

Every logging extension (like KSLog.i) have its analog with lazy inited message text and the same one with suffix S (like KSLog.iS) for the suspendable message calculation.

Default logger can be created by passing defaultTag and one of variants log level filters: set or minimal loggable level. In JVM you also may setup any logger as base logger for default realizations of KSLog. Besides, you may use your own callback (on any target platform) as output of logging:

val logger = KSLog { logLevel, optionalTag, message, optionalThrowable ->\n    println(\"[$logLevel] $optionalTag - $message: $optionalThrowable.stackTraceToString()\")\n}\n

In the example above we will take the logger which will just print incoming data as common output.

"},{"location":"kslog/index.html#installation","title":"Installation","text":""},{"location":"kslog/index.html#gradle","title":"Gradle","text":"
implementation \"dev.inmo:kslog:$kslog_version\"\n
"},{"location":"kslog/index.html#maven","title":"Maven","text":"
<dependency>\n  <groupId>dev.inmo</groupId>\n  <artifactId>kslog</artifactId>\n  <version>${kslog_version}</version>\n</dependency>\n
"},{"location":"kslog/logging.html","title":"Logging","text":"

Message type notice

On this page all the messages will be just simple String, but you may pass any object as the message

As has been said in the setup section, this library contains next levels of logging with their default representations on each platform:

Weight (by order) LogLevel name JS JVM Loggers Android 0 TRACE console.trace + console.debug Level.FINEST Log.d 1 DEBUG console.debug Level.FINER Log.d 2 VERBOSE console.info Level.FINE Log.v 3 INFO console.info Level.INFO Log.i 4 WARNING console.warn Level.WARNING Log.w 5 ERROR console.error Level.SEVERE Log.e 6 ASSERT console.error Level.SEVERE Log.wtf

Each of these levels have fullname and shortname shortcat extensions:

And any of these shortcuts may accept one of several arguments combinations:

So, when you want to log some expected exception, there are three common ways to do it:

val logger = KSLog.default\n\n// with callback\nlogger.info(tag, throwable) {\n  \"Some your message for this event\"\n}\n\n// with suspendable callback\nlogger.infoS(tag, throwable) {\n  withContext(Dispatchers.Default) {\n    \"Some your message for this event\"\n  }\n}\n\n// Just with message\nlogger.info(\"Some your message for this event\", throwable)\n\n// With message and tag as strings\nlogger.info(tag, \"Some your message for this event\", throwable)\n

Of course, any of this calls can be shortenned:

val logger = KSLog.default\n\n// with callback\nlogger.i(tag, throwable) {\n  \"Some your message for this event\"\n}\n\n// with suspendable callback\nlogger.iS(tag, throwable) {\n  withContext(Dispatchers.Default) {\n    \"Some your message for this event\"\n  }\n}\n\n// Just with message\nlogger.i(\"Some your message for this event\", throwable)\n\n// With message and tag as strings\nlogger.i(tag, \"Some your message for this event\", throwable)\n

There is special shortcat - for base performLog. In that case the only change is that you will require to pass the LogLevel more obviously:

val logger = KSLog.default\n\n// with callback\nlogger.log(LogLevel.INFO, tag, throwable) {\n  \"Some your message for this event\"\n}\n\n// with suspendable callback\nlogger.logS(LogLevel.INFO, tag, throwable) {\n  withContext(Dispatchers.Default) {\n    \"Some your message for this event\"\n  }\n}\n\n// Just with message\nlogger.log(LogLevel.INFO, \"Some your message for this event\", throwable)\n\n// With message and tag as strings\nlogger.log(LogLevel.INFO, tag, \"Some your message for this event\", throwable)\n

OR

val logger = KSLog.default\n\n// with callback\nlogger.l(LogLevel.INFO, tag, throwable) {\n  \"Some your message for this event\"\n}\n\n// with suspendable callback\nlogger.lS(LogLevel.INFO, tag, throwable) {\n  withContext(Dispatchers.Default) {\n    \"Some your message for this event\"\n  }\n}\n\n// Just with message\nlogger.l(LogLevel.INFO, \"Some your message for this event\", throwable)\n\n// With message and tag as strings\nlogger.l(LogLevel.INFO, tag, \"Some your message for this event\", throwable)\n
"},{"location":"kslog/setup.html","title":"Setup","text":""},{"location":"kslog/setup.html#dependency-installation","title":"Dependency installation","text":""},{"location":"kslog/setup.html#gradle-groovy","title":"Gradle (Groovy)","text":"
implementation \"dev.inmo:kslog:$kslog_version\"\n
"},{"location":"kslog/setup.html#gradle-kotlin-script","title":"Gradle (Kotlin Script)","text":"
implementation(\"dev.inmo:kslog:$kslog_version\")\n
"},{"location":"kslog/setup.html#maven-pom","title":"Maven (pom)","text":"
<dependency>\n  <groupId>dev.inmo</groupId>\n  <artifactId>kslog</artifactId>\n  <version>${kslog_version}</version>\n</dependency>\n
"},{"location":"kslog/setup.html#setup-in-code","title":"Setup in code","text":"

The main point in setup in your code is to setup default logger:

KSLog.default = KSLog(\"defaultTag\")\n

You may use custom messageFormatter in any of KSLog factory to customize output of KSLog logging. For example:

KSLog(\n  \"loggingWithCustomFormat\",\n  messageFormatter = { level, tag, message, throwable ->\n    println(\"[$level] $tag - $message: $throwable\")\n  }\n)\n

Additionally you may use one of several different settings:

In case you are passing minLoggingLevel, the level and more important levels will be passed to logs. For example, when you are settings up your logger as in next snippet:

val logger = KSLog(\n    \"exampleTag\",\n    minLoggingLevel = LogLevel.INFO\n)\n

The next levels will be logged with logger:

"},{"location":"kslog/setup.html#special-loggers","title":"Special loggers","text":""},{"location":"kslog/setup.html#callbackkslog","title":"CallbackKSLog","text":"

It is logger which will call incoming performLogCallback on each logging. This logger can be create simply with one callback:

KSLog { level, tag, message, throwable ->\n  println(\"[$level] $tag - $message: $throwable\")\n}\n
"},{"location":"kslog/setup.html#taglogger","title":"TagLogger","text":"

It is simple value class which can be used for zero-cost usage of some tag and calling for KSLog.default. For example, if you will create tag logger with next code:

val logger = TagLogger(\"tagLoggerTag\")\n

The logger will call KSLog.default with the tag tagLoggerTag on each calling of logging.

"},{"location":"kslog/setup.html#filterkslog","title":"FilterKSLog","text":"

This pretty simple logger will call its fallbackLogger only in cases when incoming messageFilter will return true for logging:

val baseLogger = KSLog(\"base\") // log everything with the tag `base` if not set other\nval filtered = baseLogger.filtered { _, t, _ ->\n    t == \"base\"\n}\n

In the example above baseLogger will perform logs in two ways: when it has been called directly or when we call log performing with the tag \"base\" or null. Besides, you can see there extension filtered which allow to create FilterKSLog logger with simple lambda.

"},{"location":"kslog/setup.html#typedkslog","title":"TypedKSLog","text":"

This logger accepts map of types with the target loggers. You may build this logger with the special simple DSL:

val baseLogger = KSLog(\"base\") // log everything with the tag `base` if not set other\nval typed = buildTypedLogger {\n  on<Int>(baseLogger) // log all ints to the baseLogger\n  on<Float> { _, _, message, _ ->// log all floats to the passed logger\n    println(message.toString()) // just print all floats\n  }\n  default { level, tag, message, throwable ->\n    KSLog.performLog(level, tag, message, throwable)\n  }\n}\n
"},{"location":"kslog/setup.html#automatical-loggers","title":"Automatical loggers","text":"

There are two things which can be useful in your code: logger and logTag extensions. logTag is the autocalculated by your object classname tag. logger extension can be used with applying to any object like in the next snippet:

class SomeClass {\n  init {\n    logger.i(\"inited\")\n  }\n}\n

The code above will trigger calling of logging in KSLog.default with level LogLevel.INFO using tag SomeClass and message \"inited\". As you could have guessed, logger is using TagLogger with logTag underhood and the most expensive operation here is automatical calculation of logTag.

"},{"location":"kslog/setup.html#jvm-specific-setup","title":"JVM specific setup","text":"

For JVM you may setup additionally use java loggers as the second parameter of KSLog factory. For example:

KSLog(\n  \"yourTag\"\n  Logger.getLogger(\"YourJavaLoggerName\")\n)\n
"},{"location":"micro_utils/index.html","title":"MicroUtils","text":"

MicroUtils is a set of libraries to help me (and, I hope, you too) in some routine doings of coding.

First of all, this library collection is oriented to use next technologies:

Warning

Due to complexity of this library, it is possible that some things will be missed or inactual. Me and the users of this library will try hard to keep its docs as actual as possible, but in case you will find some inconsistency of docs and library work (signatures, behaviour, API) you may write me directly in my telegram

"},{"location":"micro_utils/colors.ktstemplate.html","title":"Colors.ktstemplate","text":"

group=dev.inmo artifact=micro_utils.colors.common package=$group.$artifact central_package=$group/$artifact

"},{"location":"micro_utils/colors.ktstemplate.html#colors","title":"Colors","text":"

Adding dependency:

implementation \"$group:$artifact:latest\"\n

Info

All the samples below will represent HEXAColor with r==0xaa, g==0xff, b==0x00 and a==0xff

This package contains mainly one file: HEXAColor. This file contains unified color with HEXA format. It consumes UInt by default constructor and r/g/b/a parameters in other main constructors:

HEXAColor(0xaaff00ffu) // 0xRGBAu as UInt\nHEXAColor(r = 0xaa, g = 0xff, b = 0x00, a = 0xff)\nHEXAColor(r = 0xaa, g = 0xff, b = 0x00, aOfOne = 1f)\n

Besides, you may use one of converters:

HEXAColor.fromAhex(0xffaaff00u) // 0xARGBu as UInt\nHEXAColor.parse(\"rgba(aa, ff, 00, ff)\")\nHEXAColor.parse(\"rgba(aa, ff, 00)\")\nHEXAColor.parse(\"#af0\")\nHEXAColor.parse(\"#af0f\")\nHEXAColor.parse(\"#aaff00\")\nHEXAColor.parse(\"#aaff00ff\")\n
"},{"location":"micro_utils/colors.html","title":"Colors","text":"

Adding dependency:

implementation \"dev.inmo:micro_utils.colors.common:latest\"\n

Info

All the samples below will represent HEXAColor with r==0xaa, g==0xff, b==0x00 and a==0xff

This package contains mainly one file: HEXAColor. This file contains unified color with HEXA format. It consumes UInt by default constructor and r/g/b/a parameters in other main constructors:

HEXAColor(0xaaff00ffu) // 0xRGBAu as UInt\nHEXAColor(r = 0xaa, g = 0xff, b = 0x00, a = 0xff)\nHEXAColor(r = 0xaa, g = 0xff, b = 0x00, aOfOne = 1f)\n

Besides, you may use one of converters:

HEXAColor.fromAhex(0xffaaff00u) // 0xARGBu as UInt\nHEXAColor.parse(\"rgba(aa, ff, 00, ff)\")\nHEXAColor.parse(\"rgba(aa, ff, 00)\")\nHEXAColor.parse(\"#af0\")\nHEXAColor.parse(\"#af0f\")\nHEXAColor.parse(\"#aaff00\")\nHEXAColor.parse(\"#aaff00ff\")\n
"},{"location":"micro_utils/resources.html","title":"Resources","text":"

Package: dev.inmo:micro_utils.resources

This package aimed to make some multiplatform support for resources of your application. As for now, there is only support for strings. Sample:

object Translations {\n    val someVariable = buildStringResource(\n        \"Sample default string\"\n    ) {\n        IetfLang.German variant lazy \"Beispiel f\u00fcr eine Standardzeichenkette\"\n    }\n}\n

In this case, you will be able to use it with next logic:

Translation.someVariable.translation(IetfLang.French) // \"Sample default string\" as default one\nTranslation.someVariable.translation(IetfLang.German) // \"Beispiel f\u00fcr eine Standardzeichenkette\" as available variant\nTranslation.someVariable.translation(IetfLang.German.DE) // \"Beispiel f\u00fcr eine Standardzeichenkette\" as available parent variant\n
"},{"location":"micro_utils/resources.html#additional-opportunities-on-android-platform","title":"Additional opportunities on Android platform","text":"

On Android you may use Configuration (as well as Resources or Context) to get translation for current locale. For example:

val context: Context = // context retrieving\n\ncontext.translation(Translation.someVariable)\n
"},{"location":"micro_utils/resources.html#additional-opportunities-on-jvm-platform","title":"Additional opportunities on JVM platform","text":"

On JVM platform you usually may use Locale.getDefault() to get Locale object and pass it to translation extension:

Translation.someVariable.translation(Locale.getDefault())\nTranslation.someVariable.translation() // Locale.getDefault() hidden\n
"},{"location":"micro_utils/startup.html","title":"Startup","text":"

This package contains unified simple Plugin/Launcher tools for separating of your apps parts

"},{"location":"micro_utils/startup.html#plugin","title":"Plugin","text":"

To define plugin, you must use StartPlugin as supertype for your plugin. Restrictions are simple: plugins must be an object or class with empty constructor. Basic sample is here:

object YourPlugin : StartPlugin {\n    // Body of your plugin\n}\n

Each plugin may contains to parts:

object YourPlugin : StartPlugin {\n    override fun Module.setupDI(config: JsonObject) {\n        // here you may setup any DI content you wish to be available in context of current Koin module\n    }\n    override fun startPlugin(koin: Koin) {\n        // all staff from setupDI and the same function of other plugins is available in koin\n    }\n}\n
"},{"location":"micro_utils/startup.html#launcher","title":"Launcher","text":"

Basically, launcher module can be used to start application directly from gradle. Let\u2019s imagine you have this gradle groovy config:

plugins {\n    id 'org.jetbrains.kotlin.jvm'\n    id \"org.jetbrains.kotlin.plugin.serialization\"\n    id 'application'\n}\n\ndependencies {\n    // kotlin and other dependencies\n    implementation (\"dev.inmo:micro_utils.startup.launcher:$latest_version\")\n}\n\napplication {\n    mainClassName = 'dev.inmo.micro_utils.startup.launcher.MainKt'\n}\n

You will be able to run your project with gradle command ./gradlew run --args=\"path/to/config.json\". config.json must contains something like:

{\n    \"plugins\": [\n        \"dev.inmo.micro_utils.startup.launcher.HelloWorldPlugin\"\n    ]\n}\n

In current case you will see in logger different logs about launching including log from HelloWorldPlugin with text Hello world.

"},{"location":"micro_utils/repos/index.html","title":"Repos","text":"

Repositories in this library are unified interfaces to work with different types of standard repos:

"},{"location":"micro_utils/repos/index.html#crud","title":"CRUD","text":"

Default interface for any CRUD-oriented realization of repositories. This type of repos separated to three interfaces:

flowchart TB ReadCRUDRepo --> CRUDRepo WriteCRUDRepo --> CRUDRepo

CRUDRepo extends both ReadCRUDRepo and WriteCRUDRepo.

CRUD repos do not support forced placing of data by id when data is not in repo. That means, that you can\u2019t set data in repo by id which absent in the repository.

"},{"location":"micro_utils/repos/index.html#readcrudrepo","title":"ReadCRUDRepo","text":"

Contains read-only operations, such as getById, contains. This interface can\u2019t be observed because of it does not suppose any mutable operation.

"},{"location":"micro_utils/repos/index.html#writecrudrepo","title":"WriteCRUDRepo","text":"

Contains write-only operations, such as create, update. This interface can be observed via its flows:

Info

By default, all mutating operations consumes Lists of data (List<New> for create, List<Pair<Id, New>> for update and List<Id> for delete), but all they have their extension function-variations with one/two args (like create with New arg)

"},{"location":"micro_utils/repos/index.html#keyvalue","title":"KeyValue","text":"

Key-value repos has been created to support work with classic key-value stores, where keys are unique across all the repo when values are not unique. As well as all the others types of repos, this one have two basic types: ReadKeyValueRepo and WriteKeyValueRepo

"},{"location":"micro_utils/repos/index.html#readkeyvaluerepo","title":"ReadKeyValueRepo","text":"

Read repo provides functions like: contains, get or values.

"},{"location":"micro_utils/repos/index.html#writekeyvaluerepo","title":"WritekeyValueRepo","text":"

Contains write-only operations. This interface can be observed via its flows:

Info

By default, all mutating operations consumes some collections. For example, set require Map with Keys and Values and do not returns anything. Instead, it will throw notification via onNewValue flow

All the methods on WriteKeyValueRepo have their variances with pairs (for set) or plain varargs.

"},{"location":"micro_utils/repos/index.html#keyvalues","title":"KeyValues","text":"

This type of repos contains muliple Values by their unique Key. It is not guaranteed, that Values list by any Key will contains only unique values, but in most cases Values list will not contains copies/same objects.

"},{"location":"micro_utils/repos/index.html#readkeyvaluesrepo","title":"ReadKeyValuesRepo","text":"

Contains operations for work with value/values getting and checking. For example: count for checking of amount of all values in repo or values by key; get for getting of values by pagination.

"},{"location":"micro_utils/repos/index.html#writekeyvaluesrepo","title":"WriteKeyValuesRepo","text":"

Contains write-only operations. This interface can be observed via its flows:

Info

In difference with other repos, not all the methods of write key values repo require collections.

All the methods on WriteKeyValuesRepo have their variances with pairs (for set) or plain varargs.

"},{"location":"micro_utils/repos/inmemory.html","title":"In memory","text":"

In memory realizations contains several simple variants:

Each realization contains Write and Read parents.

There are several important moments:

"},{"location":"micro_utils/repos/inmemory.html#writemapcrudrepo-and-mapcrudrepo","title":"WriteMapCRUDRepo (and MapCRUDRepo)","text":"

It is an abstract repo with abstract functions: updateObject and createObject. Both functions require from realization to create Registered variant from incoming data and both will be called within repo locker.withWriteLock.

You may use functions MapCRUDRepo with passing the callbacks updateObject and createObject which will be used in their realizations of default MapCRUDRepo variant

"},{"location":"navigation/index.html","title":"Navigation","text":"

This library uses koin as preferred DI in MVVM part

Navigation is a library for simple management for your app views (or some other logics). In this library there are several important terms:

"},{"location":"navigation/index.html#work-explanation","title":"Work explanation","text":" Statuses

There are 4 real statuses:

In fact node will retrieve 6 changes of statuses:

flowchart TB New -.-> Create Create -.-> Created Created -.-> Start -.-> Started Started --> Resume --> Resumed Resumed --> Pause --> Started Started --> Stop --> Created Created --> Destroy Destroy --> New DashedLineLegendTitle(Dashed line) -.-> DashedLineLegend(Possible direction before `Created` state) SolidLineLegendTitle(Solid line) --> SolidLineLegend(Possible direction after `Created` state) class New navigation-new; class Destroyed navigation-new; class Created navigation-created; class Started navigation-started; class Resumed navigation-resumed;"},{"location":"navigation/index.html#nodes-behaviour","title":"Nodes behaviour","text":"

Let\u2019s see the next sample:

flowchart LR subgraph Nodes/Chains tree NodeN1(N1) NodeN2(N2) class NodeN1 navigation-started; class NodeN2 navigation-resumed; subgraph RootChain direction LR NodeN1 --> NodeN2 end class RootChain navigation-resumed; end

we may say several things about the sample above:

So, we would like to add new node in the end of stack:

flowchart LR subgraph Nodes/Chains tree NodeN1(N1) NodeN2(N2) NodeN3(N3) class NodeN1 navigation-started; class NodeN2 navigation-started; class NodeN3 navigation-resumed; subgraph RootChain direction LR NodeN1 --> NodeN2 NodeN2 --> NodeN3 end class RootChain navigation-resumed; end

As we can see, N3 became RESUMED and N2 PAUSED. Let\u2019s try to remove N3:

flowchart LR subgraph Nodes/Chains tree NodeN1(N1) NodeN2(N2) class NodeN1 navigation-started; class NodeN2 navigation-resumed; subgraph RootChain direction LR NodeN1 --> NodeN2 end class RootChain navigation-resumed; end"},{"location":"navigation/index.html#chains-behaviour","title":"Chains behaviour","text":"

So, let\u2019s continue with the sample above. Let\u2019s imagine, we need to add new subchain for N2 node. Whole tree will look like:

flowchart LR subgraph Nodes/Chains tree direction LR NodeN1(N1) NodeN2(N2) NodeN3(N3) class NodeN1 navigation-started; class NodeN2 navigation-resumed; class NodeN3 navigation-resumed; subgraph RootChain direction LR NodeN1 --> NodeN2 NodeN2 end NodeN2 --> N2Subchain subgraph N2Subchain direction LR NodeN3 end class RootChain navigation-resumed; class N2Subchain navigation-resumed; end

Here has been created new N2Subchain with N3 node. Both them resumed because of:

We may add new subchain to N1:

flowchart LR subgraph Nodes/Chains tree direction LR NodeN1(N1) NodeN2(N2) NodeN3(N3) NodeN4(N4) class NodeN1 navigation-started; class NodeN2 navigation-resumed; class NodeN3 navigation-resumed; class NodeN4 navigation-started; subgraph RootChain direction LR NodeN1 --> NodeN2 NodeN2 end NodeN1 --> N1Subchain NodeN2 --> N2Subchain subgraph N1Subchain direction LR NodeN4 end subgraph N2Subchain direction LR NodeN3 end class RootChain navigation-resumed; class N1Subchain navigation-started; class N2Subchain navigation-resumed; end

So, it has been added, but:

And now we may remove N2 node. This action will trigger next changes:

flowchart LR subgraph Changes subgraph OldNodesChainsTree [Old Nodes/Chains tree] direction TB OldNodeN1(N1) OldNodeN2(N2) OldNodeN3(N3) OldNodeN4(N4) class OldNodeN1 navigation-started; class OldNodeN2 navigation-created; class OldNodeN3 navigation-created; class OldNodeN4 navigation-started; subgraph OldRootChain [RootChain] direction TB OldNodeN1 --> OldNodeN2 OldNodeN2 end OldNodeN1 --> OldN1Subchain OldNodeN2 --> OldN2Subchain subgraph OldN1Subchain [N1Subchain] direction TB OldNodeN4 end subgraph OldN2Subchain [N2Subchain] direction TB OldNodeN3 end class OldRootChain navigation-resumed; class OldN1Subchain navigation-started; class OldN2Subchain navigation-created; end subgraph NewNodesChainsTree [New Nodes/Chains tree] direction TB NewNodeN1(N1) NewNodeN4(N4) class NewNodeN1 navigation-resumed; class NewNodeN4 navigation-resumed; subgraph NewRootChain [RootChain] direction TB NewNodeN1 end NewNodeN1 ---> NewN1Subchain subgraph NewN1Subchain [N1Subchain] direction TB NewNodeN4 end class NewRootChain navigation-resumed; class NewN1Subchain navigation-resumed; end %% OldNodesChainsTree -.-> NewNodesChainsTree OldNodeN1-.->|Become resumed| NewNodeN1 OldNodeN4-.->|Become resumed| NewNodeN4 end

What has happened:

  1. We solved to remove N2 node. Status is changing to stopped
  2. N2Subchain must be stopped
  3. N3 must be stopped as well

Stopping in context of navigation means destroying

"},{"location":"navigation/index.html#large-tree-sample","title":"Large tree sample","text":"flowchart TB NodeN1(N1) NodeN2(N2) NodeN3(N3) class NodeN1 navigation-started; class NodeN2 navigation-started; class NodeN3 navigation-resumed; subgraph RootChain direction TB NodeN1-->NodeN2 NodeN2-->NodeN3 end class RootChain navigation-resumed; NodeN4(N4) NodeN5(N5) NodeN6(N6) class NodeN4 navigation-started; class NodeN5 navigation-started; class NodeN6 navigation-started; subgraph N2Subchain direction TB NodeN4-->NodeN5 NodeN5-->NodeN6 end class N2Subchain navigation-started; NodeN2 --> N2Subchain NodeN7(N7) NodeN8(N8) class NodeN7 navigation-started; class NodeN8 navigation-resumed; subgraph N3Subchain direction TB NodeN7 --> NodeN8 end class N3Subchain navigation-resumed; NodeN3 --> N3Subchain NodeN9(N9) NodeN10(N10) class NodeN9 navigation-started; class NodeN10 navigation-resumed; subgraph N3Subchain2 direction TB NodeN9 --> NodeN10 end class N3Subchain2 navigation-resumed; NodeN3 --> N3Subchain2"},{"location":"navigation/getting-started.html","title":"Getting started (TBD)","text":"

Traditionally, you need to add dependency to your project. Currently, there are two types of artifacts:

Artifact Purpose Dependency Core Only necessary tools for your projects implementation \"dev.inmo:navigation.core:$navigation_version\" MVVM Model-View-ViewModel architecture tools + Core components implementation \"dev.inmo:navigation.mvvm:$navigation_version\""},{"location":"navigation/getting-started.html#get-started","title":"Get started","text":"

After you have added your dependency, you should initialize navigation. There are several important things:

  1. Config - it is an instance of any class which extending the NavigationNodeDefaultConfig in common case
  2. Factory - usually object which may create a node or some required part for node

For example: lets imagine that we have a node Main. Here what should we do to create a node and make it workable in navigation:

data class MainConfig(\n    // this id will be used to search an html element by id in JS\n    // and Fragment by tag in Android\n    override val id: String = \"main\"\n) : NavigationNodeDefaultConfig\n

Both JS and Android platforms require ViewModel for their MVVM node variants, but it can be common as well as MainConfig:

class MainViewModel(\n    node: NavigationNode<MainConfig, NavigationNodeDefaultConfig>\n) : ViewModel(\n    node\n)\n
"},{"location":"navigation/getting-started.html#js-part","title":"JS part","text":"
// Core variant without MVVM or Compose\nclass MainNode(\n    config: MainConfig,\n    chain: NavigationChain<NavigationNodeDefaultConfig>,\n) : JsNavigationNode<MainConfig, NavigationNodeDefaultConfig>(\n    chain,\n    config\n) {\n    // Some code\n    // In htmlElementStateFlow will be found `HTMLElement` where node should be binded\n}\n// MVVM Compose variant\nclass MainNodeView(\n    config: MainConfig,\n    chain: NavigationChain<NavigationNodeDefaultConfig>,\n) : View<MainConfig, MainViewModel>(\n    config,\n    chain\n) {\n    // Some code\n    // In htmlElementStateFlow will be found `HTMLElement` where node should be binded\n\n    @Composable\n    override onDraw() {\n        Text(\"Hello world\")\n    }\n}\n\nobject MainNodeFactory : NavigationNodeFactory<NavigationNodeDefaultConfig> {\n    override fun createNode(\n        navigationChain: NavigationChain<NavigationNodeDefaultConfig>,\n        config: NavigationNodeDefaultConfig\n    ): NavigationNode<out NavigationNodeDefaultConfig, NavigationNodeDefaultConfig>? = if (config is MainConfig) {\n        MainNode(config, navigationChain) // Or `MainNodeView(config, chain)` for MVVM\n    } else {\n        null\n    }\n}\n

Data below is under TBD

"},{"location":"navigation/getting-started.html#android","title":"Android","text":"

In Android there is one important note: you will not directly work with nodes. In fact it will be required to create special NodeFragment:

// Core variant\nclass MainFragment : NodeFragment<MainConfig, NavigationNodeDefaultConfig>() {\n    // Your code\n    // Here will be available: node with type `AndroidFragmentNode`, config: `MainConfig`\n}\n// MVVM Variant\nclass MainViewFragment : ViewFragment<MainViewModel, MainConfig>() {\n    // Will be available also `viewModel` via koin `lazyInject`\n    override val viewModelClass\n        get() = MainViewModel::class\n}\n

Initialization is different on the platforms, so, lets take a look at each one.

"},{"location":"navigation/getting-started.html#js","title":"JS","text":"

In JavaScript it looks like:

initNavigation<NavigationNodeDefaultConfig>(\n    ConfigHolder.Chain( // (1)\n        ConfigHolder.Node( // (2)\n            MainConfig(), // (3)\n            null, // (4)\n            listOf() // (5)\n        ),\n    ),\n    configsRepo = CookiesNavigationConfigsRepo( // (6)\n        Json {\n            ignoreUnknownKeys = true\n            serializersModule = SerializersModule {\n                polymorphic(NavigationNodeDefaultConfig::class, MainConfig::class, MainConfig.serializer()) // (7)\n            }\n        },\n        ConfigHolder.serializer(NavigationNodeDefaultConfig::class.serializer())\n    ),\n    dropRedundantChainsOnRestore = true, // (8)\n    nodesFactory = MainNodeFactory, // (9)\n)\n
  1. Creating of default root chain config holder. It must be root chain because of the chain work with statuses changes
  2. Creating of default root node config holder. This type contains config of the first node, its subnode and subchains lists
  3. Default root config
  4. Subnode of root node. In this case it is null, but can be any ConfigHolder.Node
  5. Subchains of default root node
  6. Configurations changes repo saver. By default it is cookies (localStorage) store
  7. Register config for serialization to let configs repo serializer to know how to serialize MainConfig
  8. Flag that the chains without any node will be dropped automatically
  9. In fact here can be factory aggregator, for example:
    val factories: List<NavigationNodeFactory<NavigationNodeDefaultConfig>>\nNavigationNodeFactory<NavigationNodeDefaultConfig> { chainHolder, config ->\n    factories.firstNotNullOfOrNull { it.createNode(chainHolder, config) }\n}\n
"},{"location":"plagubot/index.html","title":"PlaguBot","text":"

PlaguBot is a small framework for unifying developing of modules of bots. It is built with two parts:

"},{"location":"plagubot/index.html#plugin","title":"Plugin","text":"

Plugin is a partially independent part of bot. Plugin have several parts:

Plugin realization should be an object or class with empty constructor.

"},{"location":"plagubot/index.html#bot","title":"Bot","text":"

Most important of bot is main function (full reference: dev.inmo.plagubot.AppKt). It consumes one argument - path to config.

Bot is initializing with the next algorithm:

flowchart TB main[\"Main\"] Join[\"Endless join bot work\"] subgraph ConfigReading direction LR ConfigJsonParsing[\"Parsing to Json\"] ConfigParsing[\"Parsing to global config\"] ConfigJsonParsing --> ConfigParsing end ConfigReading[\"Reading of config\"] BotConstructorCalling[\"Calling of PlaguBot constructor\"] subgraph BotStart direction TB BotStartKoinAppInit[\"Initialization of koin app\"] subgraph BotStartSetupDI direction LR subgraph BotStartSetupDIPutDefaults[\"Put defaults in DI\"] direction LR BotStartSetupDIPutDefaultsConfig[\"Config\"] BotStartSetupDIPutDefaultsPluginsList[\"Plugins list\"] BotStartSetupDIPutDefaultsDatabaseConfig[\"Database Config\"] BotStartSetupDIPutDefaultsDefaultJson[\"Default Json\"] BotStartSetupDIPutDefaultsPlagubot[\"PlaguBot itself\"] BotStartSetupDIPutDefaultsTelegramBot[\"TelegramBot\"] end BotStartSetupDIIncludes[\"`Synchronous (in queue) registration of all plugins __setupDI__ modules`\"] BotStartSetupDIPutDefaults --> BotStartSetupDIIncludes end BotStartKoinAppStart[\"`Starting of koin application. Since this step all modules from __setupDI__ of plugins will be available`\"] subgraph BotStartBehaviourContextInitialization[\"Initialization of behaviour context\"] direction TB BotStartBehaviourContextInitializationStatesManager[\"`Get from DI or create default **DefaultStatesManagerRepo**`\"] BotStartBehaviourContextInitializationStatesManagerRepo[\"`Get from DI or create default **StatesManagerRepo**`\"] BotStartBehaviourContextInitializationStatesManagerUsedCondition{\"Is the default one used?\"} BotStartBehaviourContextInitializationOnStartConflictsResolver[\"Getting of all OnStartContextsConflictResolver\"] BotStartBehaviourContextInitializationOnUpdateConflictsResolver[\"Getting of all OnUpdateContextsConflictResolver\"] BotStartBehaviourContextInitializationStateHandlingErrorHandler[\"`Get from DI or create default **StateHandlingErrorHandler**`\"] subgraph BotStartBehaviourContextInitializationSetupPlugins[\"Plugins bot functionality init\"] BotStartBehaviourContextInitializationSetupPluginsSetupBotPlugin[\"`Call **setupBotPlugin** for each plugin`\"] end BotStartBehaviourContextInitializationStatesManager --> BotStartBehaviourContextInitializationStatesManagerUsedCondition BotStartBehaviourContextInitializationStatesManagerUsedCondition --\"Yes\"--> BotStartBehaviourContextInitializationStatesManagerRepo BotStartBehaviourContextInitializationStatesManagerUsedCondition --\"No\"--> BotStartBehaviourContextInitializationStateHandlingErrorHandler BotStartBehaviourContextInitializationStatesManagerRepo --> BotStartBehaviourContextInitializationOnStartConflictsResolver BotStartBehaviourContextInitializationOnStartConflictsResolver --> BotStartBehaviourContextInitializationOnUpdateConflictsResolver BotStartBehaviourContextInitializationOnUpdateConflictsResolver --> BotStartBehaviourContextInitializationStateHandlingErrorHandler BotStartBehaviourContextInitializationStateHandlingErrorHandler --> BotStartBehaviourContextInitializationSetupPlugins end BotStartDeleteWebhook[\"Delete webhooks\"] BotStartStartLongPolling[\"Start long polling\"] BotStartKoinAppInit --> BotStartSetupDI BotStartSetupDI --> BotStartKoinAppStart BotStartKoinAppStart --> BotStartBehaviourContextInitialization BotStartBehaviourContextInitialization --> BotStartDeleteWebhook BotStartDeleteWebhook --> BotStartStartLongPolling end main --> ConfigReading ConfigReading --> BotConstructorCalling BotConstructorCalling --> BotStart BotStart --> Join"},{"location":"plagubot/opportunities_out_of_the_box.html","title":"Opportunities out of the box","text":"

There are several important opportunities out of the box:

"},{"location":"plagubot/opportunities_out_of_the_box.html#database-access","title":"Database access","text":"

You may access database in your plugin via koin in setupBotPlugin or as parameter in setupDI:

object YourPlugin : Plugin {\n    // ...\n    override fun Module.setupDI(\n        database: Database, // database\n        params: JsonObject\n    ) {\n        // ...\n    }\n}\n

It is simple Exposed database and you may use it in your tables.

"},{"location":"plagubot/opportunities_out_of_the_box.html#config-access","title":"Config access","text":"

As you may see, in the setupDI function we also have params parameter with source configuration json. In case you wish to declare and work with your own config in plugin, you may use next snippet:

object YourPlugin : Plugin {\n    @Serializable\n    data class MyConfig(\n        val param1: String,\n        val param2: Int,\n    )\n    // ...\n    override fun Module.setupDI(\n        database: Database, // database\n        params: JsonObject\n    ) {\n        single {\n            get<Json>().decodeFromJsonElement(MyConfig.serializer(), params) // register from root (1)\n        }\n        // OR\n        single {\n            get<Json>().decodeFromJsonElement(MyConfig.serializer(), params[\"yourplugin\"]!!) // register from field \"yourplugin\" (2)\n        }\n        // ...\n    }\n\n    override suspend fun BehaviourContext.setupBotPlugin(\n        koin: Koin\n    ) {\n        koin.get<MyConfig>() // getting of registered config\n    }\n}\n
  1. In this case your config will looks like:
    {\n  \"params1\": \"SomeString\",\n  \"params2\": 42\n}\n
  2. In this case your config will looks like:
    {\n  \"yourplugin\": {\n    \"params1\": \"SomeString\",\n    \"params2\": 42\n  }\n}\n
"},{"location":"plagubot/opportunities_out_of_the_box.html#bot-setup","title":"Bot setup","text":"

Out of the box you may setup several things in bot:

  1. For this use next code in setupDI:
    // Your plugin\n    override fun Module.setupDI(database: Database, params: JsonObject) {\n        single<StatesManager<State>> {\n            // Your StatesManager<State> initialization\n        }\n    }\n
  2. For this use next code in setupDI:
    // Your plugin\n    override fun Module.setupDI(database: Database, params: JsonObject) {\n        single<DefaultStatesManagerRepo<State>> {\n            // Your DefaultStatesManagerRepo<State> initialization\n        }\n    }\n
  3. You may declare any amount of OnStartContextsConflictResolver. PlaguBot will take first non-null result of resolvers from DI and use in default states manager. To declare, use next snippet:
    // Your plugin\n    override fun Module.setupDI(database: Database, params: JsonObject) {\n        singleWithRandomQualifier<OnStartContextsConflictResolver> {\n            OnStartContextsConflictResolver { old, new ->\n                // null|true|false\n            }\n        }\n    }\n
  4. You may declare any amount of OnUpdateContextsConflictResolver. PlaguBot will take first non-null result of resolvers from DI and use in default states manager. To declare, use next snippet:
    // Your plugin\n    override fun Module.setupDI(database: Database, params: JsonObject) {\n        singleWithRandomQualifier<OnUpdateContextsConflictResolver> {\n            OnUpdateContextsConflictResolver { old, new, currentStateOnContext ->\n                // null|true|false\n            }\n        }\n    }\n
  5. You may declare only one StateHandlingErrorHandler<State>. This handler will be called each time when some state will be handled with exception and may return null or new state instead old one:
    // Your plugin\n    override fun Module.setupDI(database: Database, params: JsonObject) {\n        single<StateHandlingErrorHandler<State>> {\n            StateHandlingErrorHandler<State> { state, throwable ->\n                // null or State\n            }\n        }\n    }\n
"},{"location":"services/index.html","title":"Services information","text":"

There are several public services I am hosting or have created:

  1. I am using this tool in all my libraries :)
"},{"location":"services/index.html#tools","title":"Tools","text":""},{"location":"services/index.html#services","title":"Services","text":""},{"location":"services/index.html#kdocs","title":"KDocs","text":""},{"location":"tgbotapi/index.html","title":"TelegramBotAPI","text":"

Hello! This is a set of libraries for working with Telegram Bot API.

"},{"location":"tgbotapi/index.html#examples","title":"Examples","text":"

There are several things you need to do to launch examples below:

More including instructions available here. Other configuration examples:

"},{"location":"tgbotapi/index.html#most-common-example","title":"Most common example","text":"
suspend fun main() {\n  val bot = telegramBot(TOKEN)\n\n  bot.buildBehaviourWithLongPolling {\n    println(getMe())\n\n    onCommand(\"start\") {\n      reply(it, \"Hi:)\")\n    }\n  }.join()\n}\n

In this example you will see information about this bot at the moment of starting and answer with Hi:) every time it gets message /start

"},{"location":"tgbotapi/index.html#handling-only-last-messages","title":"Handling only last messages","text":"
suspend fun main() {\n  val bot = telegramBot(TOKEN)\n\n  val flowsUpdatesFilter = FlowsUpdatesFilter()\n  bot.buildBehaviour(flowUpdatesFilter = flowsUpdatesFilter) {\n    println(getMe())\n\n    onCommand(\"start\") {\n      reply(it, \"Hi:)\")\n    }\n\n    retrieveAccumulatedUpdates(this).join()\n  }\n}\n

The main difference with the previous example is that bot will get only last updates (accumulated before bot launch and maybe some updates it got after launch)

"},{"location":"tgbotapi/index.html#build-a-little-bit-more-complex-behaviour","title":"Build a little bit more complex behaviour","text":"
suspend fun main() {\n  val bot = telegramBot(TOKEN)\n\n  bot.buildBehaviourWithLongPolling {\n    println(getMe())\n\n    val nameReplyMarkup = ReplyKeyboardMarkup(\n      matrix {\n        row {\n          +SimpleKeyboardButton(\"nope\")\n        }\n      }\n    )\n    onCommand(\"start\") {\n      val photo = waitPhoto(\n        SendTextMessage(it.chat.id, \"Send me your photo please\")\n      ).first()\n\n      val name = waitText(\n        SendTextMessage(\n          it.chat.id,\n          \"Send me your name or choose \\\"nope\\\"\",\n          replyMarkup = nameReplyMarkup\n        )\n      ).first().text.takeIf { it != \"nope\" }\n\n      sendPhoto(\n        it.chat,\n        photo.mediaCollection,\n        entities = buildEntities {\n          if (name != null) regular(name) // may be collapsed up to name ?.let(::regular)\n        }\n      )\n    }\n  }.join()\n}\n
"},{"location":"tgbotapi/index.html#more-examples","title":"More examples","text":"

You may find examples in this project. Besides, you are always welcome in our chat.

"},{"location":"tgbotapi/faq.html","title":"FAQ","text":""},{"location":"tgbotapi/faq.html#what-is-the-error-failed-to-load-class-orgslf4jimplstaticloggerbinder","title":"What is the error Failed to load class \"org.slf4j.impl.StaticLoggerBinder\"?","text":"
SLF4J: Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".\nSLF4J: Defaulting to no-operation (NOP) logger implementation\nSLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.\n

This error is just a warning about the absence of slf4j setup. You may fix this error by following to stackoverflow answer

"},{"location":"tgbotapi/faq.html#how-to-filter-updates-in-some-part-of-behaviourbuilder","title":"How to filter updates in some part of BehaviourBuilder?","text":"

You may create subcontext with BehaviourBuilder.createSubContextAndDoWithUpdatesFilter and pass there updatesUpstreamFlow parameter with any operations over parent behaviour builder:

buildBehaviourWithLongPolling {\n    createSubContextAndDoWithUpdatesFilter(\n        updatesUpstreamFlow = filter { /* some condition */ },\n        stopOnCompletion = false // disable stopping of sub context after setup\n    ) {\n        onCommand() //...\n    }\n}\n
"},{"location":"tgbotapi/faq.html#additional-info","title":"Additional info","text":""},{"location":"tgbotapi/faq.html#cases","title":"Cases","text":""},{"location":"tgbotapi/logs.html","title":"Logging","text":"

In this library we are using KSLog for logging of events in telegram bots. There are several ways to set it up and configure.

// (1)\nsetDefaultKSLog(\n    KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->\n        println(defaultMessageFormatter(level, tag, message, throwable))\n    }\n)\n\n// (2)\nDefaultKTgBotAPIKSLog = KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->\n    println(defaultMessageFormatter(level, tag, message, throwable))\n}\n\n// (3)\nval bot = telegramBot(YOUR_TOKEN) {\n    logger = KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->\n        println(defaultMessageFormatter(level, tag, message, throwable))\n    }\n}\n
  1. This variant will set GLOBAL DEFAULT logger. For example, if you will use somewhere TagLogger, it will use KSLog.default under the hood
  2. All the bots created after this setup will use new logger until more specified logger configured (see below)
  3. Passing of logger variable to the KtorRequestsExecutor or one of factories telegrabBot will lead to granular setup of logging
"},{"location":"tgbotapi/dsls/keyboards.html","title":"Keyboards","text":"

In the telegram system there are two types of keyboards:

Reply Inline Keyboard for each user in the chat Keyboard linked to the certain message

Low-level way to create keyboard looks like in the next snippet:

ReplyKeyboardMarkup(\n    matrix {\n        row {\n            add(SimpleKeyboardButton(\"Simple text\"))\n            // ...\n        }\n        // ...\n    }\n)\n

In case you wish to create inline keyboard, it will look like the same as for reply keyboard. But there is another way. The next snippet will create the same keyboard as on the screenshots above:

// reply keyboard\nreplyKeyboard {\n    row {\n        simpleButton(\"7\")\n        simpleButton(\"8\")\n        simpleButton(\"9\")\n        simpleButton(\"*\")\n    }\n    row {\n        simpleButton(\"4\")\n        simpleButton(\"5\")\n        simpleButton(\"6\")\n        simpleButton(\"/\")\n    }\n    row {\n        simpleButton(\"1\")\n        simpleButton(\"2\")\n        simpleButton(\"3\")\n        simpleButton(\"-\")\n    }\n    row {\n        simpleButton(\"0\")\n        simpleButton(\".\")\n        simpleButton(\"=\")\n        simpleButton(\"+\")\n    }\n}\n\n// inline keyboard\ninlineKeyboard {\n    row {\n        dataButton(\"Get random music\", \"random\")\n    }\n    row {\n        urlButton(\"Send music to friends\", \"https://some.link\")\n    }\n}\n
"},{"location":"tgbotapi/dsls/live-location.html","title":"Live Location","text":"

Bot API allows you to send live locations and update them during their lifetime. In this library there are several ways to use this API:

"},{"location":"tgbotapi/dsls/live-location.html#sendlivelocation","title":"sendLiveLocation","text":"

In the Bot API there is no independent sendLiveLocation method, instead it is suggested to use sendLocation with setting up live_period. In this library in difference with original Bot API live location is special request. It was required because of in fact live locations and static locations are different types of location info and you as bot developer may interact with them differently.

Anyway, in common case the logic looks like:

"},{"location":"tgbotapi/dsls/live-location.html#startlivelocation","title":"startLiveLocation","text":"

In difference with sendLiveLocation, startLiveLocation using LiveLocationProvider. With this provider you need not to handle chat and message ids and keep some other data for location changes. Instead, you workflow with provider will be next:

Besides, LiveLocationProvider contains different useful parameters about live location

"},{"location":"tgbotapi/dsls/live-location.html#handlelivelocation","title":"handleLiveLocation","text":"

This way of live locations handling is based on coroutines Flow and allow you to pass some external Flow with EditLiveLocationInfo. So, workflow:

See our example to get more detailed sample

"},{"location":"tgbotapi/dsls/text.html","title":"Text","text":"

For the text creating there are several tools. The most simple one is to concatenate several text sources to make list of text sources as a result:

val sources = \"Regular start of text \" + bold(\"with bold part\") + italic(\"and italic ending\")\n

But there is a little bit more useful way: entities builder:

val items = (0 until 10).map { it.toString() }\nbuildEntities(\" \") {// optional \" \" auto separator which will be pasted between text sources\n    +\"It is regular start too\" + bold(\"it is bold as well\")\n    items.forEachIndexed { i, item ->\n        if (i % 2) {\n            italic(item)\n        } else {\n            strikethrough(item)\n        }\n    }\n}\n

In the code above we are creating an items list just for demonstrating that inside of buildEntities body we may use any operations for cunstructing our result list of TextSources. As a result, will be created the list which will looks like in telegram as \u201cIt is regular start too it is bold as well 0 ~~1~~ 2 ~~3~~ 4 ~~5~~ 6 ~~7~~ 8 ~~9~~\u201d.

"},{"location":"tgbotapi/guides/keyboards.html","title":"Keyboards Guide","text":"

This guide will help you choose the right keyboard for your needs and show you various API facilities available in the library to support your choice.

"},{"location":"tgbotapi/guides/keyboards.html#introduction","title":"Introduction","text":""},{"location":"tgbotapi/guides/keyboards.html#keyboard-types","title":"Keyboard Types","text":"

The first thing you need to know is that there are two types of keyboards available in the Telegram Bot API: reply and inline keyboards.

Resize option

In the screenshots above (and in the most others) you may see usage of reply keyboards without resize_keyboard. In case you will use resize_keyboard = true the keyboard will be smaller.

Note the differences in the way these keyboards are shown to a user.

A reply keyboard is shown under the message input field. It replaces the device\u2019s native input method on a mobile device.

An inline keyboard is shown as a part of the message in the chat.

"},{"location":"tgbotapi/guides/keyboards.html#simple-keyboard-interactions","title":"Simple Keyboard Interactions","text":"

When a user clicks on a simple reply keyboard button, its text is just sent in the chat.

When a user clicks on a simple inline keyboard button, nothing is sent to the chat. Instead, a callback query (a fancy way to say \u201ca request\u201d) is sent directly to the bot and the button is highlighted. It will stay highlighted until the bot acks the callback.

It\u2019s a common mistake to forget to handle callback queries

It leads to the buttons being highlighted for long periods of time, which leads to a bad user experience. Don\u2019t forget to handle these callbacks!

As new messages arrive, a reply keyboard will stay there, while the inline keyboard will stick to the message and move with it.

Ups\u2026 The reply keyboard is now far away from the message it was sent with.

Actually, they are two different unrelated entities now: the original message and the reply keyboard. A reply keyboard persists until you explicitly remove it or replace it with a different one.

It\u2019s a common mistake to forget to remove or replace reply keyboards

It leads to the keyboards being shown forever. Don\u2019t forget to remove reply keyboards when you don\u2019t need them anymore!

You also may use option one_time_keyboard and the keyboard will be automatically removed after user interaction

An inline keyboard could also be removed or changed by editing the original message it was attached to.

"},{"location":"tgbotapi/guides/keyboards.html#extended-keyboard-interactions","title":"Extended Keyboard Interactions","text":"

Keyboards are not limited to text only. They could be used to ask users for different things, like payments, locations, phone numbers, etc. They could be used to open arbitrary URLs or web apps. Telegram clients process these buttons and interact with the users in the appropriate ways.

For the full list of options, see the official documentation on reply and inline keyboards.

"},{"location":"tgbotapi/guides/keyboards.html#basic-api-classes","title":"Basic API & Classes","text":"

Now, that you know the basics, let\u2019s see how to use the library.

"},{"location":"tgbotapi/guides/keyboards.html#keyboards","title":"Keyboards","text":"

In Telegram Bot API keyboards are sent to the user as a part of an interaction via the reply_markup parameter. More specifically, this parameter is available:

Tip

editMessageReplyMarkup is specifically designed to edit a message\u2019s inline keyboard.

Sending inline keyboards is also supported in inline mode through the reply_markup parameter of the InlineQueryResult type and its inheritors. However, this inline mode is unrelated to the inline keyboards.

The reply_markup parameter accepts four different types. Two of them \u2014 ReplyKeyboardMarkup and InlineKeyboardMarkup \u2014 correspond to the reply and inline keyboards respectively. The ReplyKeyboardRemove type is used to remove reply keyboards, but it\u2019s not a keyboard itself. The last one, ForceReply, is used to force users to reply to the bot. It is not a keyboard either, but yet another dirty hack employed by the Telegram Bot API.

Now, in the library, the WithReplyMarkup is a marker interface for all the interactions which could have a replyMarkup (represents reply_markup) parameter. It is extended by the ReplyingMarkupSendMessageRequest, and then, finally, by classes like SendTextMessage. This, basically, corresponds to the Telegram Bot API.

Note

You may see all the inheritors of WithReplyMarkup interfaces in the corresponding KDoc

The other way to send a keyboard is through the replyMarkup parameter of the numerous extension methods, like sendMessage. Those are just convenient wrappers around general interaction classes, like the aforementioned SendTextMessage.

"},{"location":"tgbotapi/guides/keyboards.html#buttons","title":"Buttons","text":"

As we already know, keyboards consist of buttons. Button classes reside in the dev.inmo.tgbotapi.types.buttons package.

The base class for the reply keyboard buttons is the KeyboardButton. The base class for the inline keyboard buttons is the InlineKeyboardButton.

See their inheritors for the full list of the available buttons. The names are pretty self-explanatory and correspond to the Telegram Bot API.

For example, to send a simple reply keyboard button, use the SimpleKeyboardButton class. To request a contact from the user through the reply, use the RequestContactKeyboardButton class. To attach a URL button to the message, use the URLInlineKeyboardButton. And to attach a callback button, use the CallbackDataInlineKeyboardButton.

You get the idea.

So, to send a reply keyboard use the following code:

bot.sendMessage(\n    chatId = chat,\n    text = \"What is the best Kotlin Telegram Bot API library?\",\n    replyMarkup = ReplyKeyboardMarkup(\n        keyboard = listOf(\n            listOf(\n                SimpleKeyboardButton(\"ktgbotapi\"),\n            ),\n        )\n    )\n)\n

And here is how you send a basic inline keyboard:

bot.sendMessage(\n    chatId = chat,\n    text = \"ktgbotapi is the best Kotlin Telegram Bot API library\",\n    replyMarkup = InlineKeyboardMarkup(\n        keyboard = listOf(\n            listOf(\n                CallbackDataInlineKeyboardButton(\"I know\", \"know\"),\n                URLInlineKeyboardButton(\"Learn more\", \"https://github.com/InsanusMokrassar/ktgbotapi\")\n            ),\n        )\n    ),\n)\n

When we\u2019re done with this simple quiz, we can remove the keyboard with the following code:

bot.sendMessage(\n    chatId = chat,\n    text = \"You're goddamn right!\",\n    replyMarkup = ReplyKeyboardRemove()\n)\n

Note

Don\u2019t forget to remove the reply keyboards!

"},{"location":"tgbotapi/guides/keyboards.html#matrices","title":"Matrices","text":"

Buttons in keyboards are arranged in matrices, i.e. two-dimensional arrays, or, to say in layperson\u2019s terms, rows and columns. In contrast to the matrices you\u2019ve learned in school, keyboards are not always necessarily square. Try it:

bot.sendMessage(\n    chatId = chat,\n    text = \"In contrast to the matrices you've learned in school, keyboards are not always necessary square.\",\n    replyMarkup = InlineKeyboardMarkup(\n        keyboard = listOf(\n            listOf(\n                CallbackDataInlineKeyboardButton(\"1\", \"1\"),\n                CallbackDataInlineKeyboardButton(\"2\", \"2\"),\n                CallbackDataInlineKeyboardButton(\"3\", \"3\"),\n            ),\n            listOf(\n                CallbackDataInlineKeyboardButton(\"4\", \"4\"),\n                CallbackDataInlineKeyboardButton(\"5\", \"5\"),\n            ),\n            listOf(\n                CallbackDataInlineKeyboardButton(\"6\", \"6\"),\n            )\n        )\n    )\n)\n

This way of building matrices is not very convenient, so the library provides a few eloquent DSLs to simplify that.

First, there are matrix and row, so the keyboard above can be built like this:

bot.sendMessage(\n    chatId = chat,\n    text = \"DSLs are sweet!\",\n    replyMarkup = InlineKeyboardMarkup(\n        keyboard = matrix {\n            row {\n                +CallbackDataInlineKeyboardButton(\"1\", \"1\")\n                +CallbackDataInlineKeyboardButton(\"2\", \"2\")\n                +CallbackDataInlineKeyboardButton(\"3\", \"3\")\n            }\n            row(\n                CallbackDataInlineKeyboardButton(\"4\", \"4\"),\n                CallbackDataInlineKeyboardButton(\"5\", \"5\"),\n            )\n            row {\n                +CallbackDataInlineKeyboardButton(\"6\", \"6\")\n            }\n        },\n    )\n)\n

Note

Those plus signs are mandatory.

Note

There are two different row functions here. Can you spot the difference?

A single-row matrix can be built with a flatMatrix:

flatMatrix {\n    +CallbackDataInlineKeyboardButton(\"1\", \"1\")\n    +CallbackDataInlineKeyboardButton(\"2\", \"2\")\n    +CallbackDataInlineKeyboardButton(\"3\", \"3\")\n    +CallbackDataInlineKeyboardButton(\"4\", \"4\")\n    +CallbackDataInlineKeyboardButton(\"5\", \"5\")\n}\n

But the most convenient way to build a simple keyboard is to use the constructor-like methods: InlineKeyboardMarkup and ReplyKeyboardMarkup. Note, that they are named just like the corresponding constructor, but take a vararg of buttons. They create flat matrices, i.e. single rows.

"},{"location":"tgbotapi/guides/keyboards.html#keyboards-dsl","title":"Keyboards DSL","text":"

Finally, there are inlineKeyboard and replyKeyboard

DSL methods above rely on Kotlin\u2019s feature of receivers and extensions. So, the magic is done by MatrixBuilder and RowBuilder. That\u2019s why you must use the plus sign to add buttons to the matrix: it\u2019s just an overloaded operator call, another cool Kotlin feature widely used to create sweet DSLs.

Another bonus of using these DSLs is button builders, like payButton, dataButton, and urlButton:

bot.sendMessage(\n    chatId = chat,\n    text = \"All in one!\",\n    replyMarkup = InlineKeyboardMarkup(\n        keyboard = matrix {\n            row {\n                payButton(\"Send money\")\n                dataButton(\"Ok\", \"ok\")\n                urlButton(\"Google\", \"https://google.com\")\n            }\n        },\n    )\n)\n

Reply keyboard builders provide similar extensions, e.g. requestLocationButton.

So, choose the style you like \u2014 from plain Kotlin lists to sweet DSLs \u2014 and use it!

"},{"location":"tgbotapi/guides/keyboards.html#working-with-keyboards","title":"Working with keyboards","text":"

Working with keyboards is not something special in Telegram Bot API. As you have already seen, keyboards are just message parameters. Similarly, keyboard interactions are represented by regular Updates. I.e. when a user interacts with a keyboard, the bot receives an update.

On the other hand, the library is heavily typed, so the actual type of update you would receive varies.

"},{"location":"tgbotapi/guides/keyboards.html#reply-keyboards","title":"Reply keyboards","text":"

As it was said, reply keyboards cause Telegram clients to send regular messages back to the bot. Peruse this example:

bot.buildBehaviourWithLongPolling {\n    bot.sendMessage(\n        chatId = chat,\n        text = \"\ud83d\udc6e Turn in your accomplices or be prepared for a lengthy \ud83c\udf46 incarceration \u26d3 \ud83d\udc4a \u203c\",\n        replyMarkup = replyKeyboard {\n            +SimpleKeyboardButton(\n                \"I ain't no rat! \ud83d\udeab\ud83d\udc00\ud83e\udd10\ud83d\ude45\"\n            )\n            +RequestUserKeyboardButton(\n                \"Rat out \ud83d\udc00 a friend \ud83d\udc64\",\n                KeyboardButtonRequestUser.Common(RequestId.random())\n            )\n            +RequestChatKeyboardButton(\n                \"Rat out \ud83d\udc00 a group of friends \ud83d\udc65\",\n                KeyboardButtonRequestChat.Group(RequestId.random())\n            )\n        }\n    )\n\n    onText { message: CommonMessage<TextContent> ->\n        assert(message.text == \"I ain't no rat! \ud83d\udeab\ud83d\udc00\ud83e\udd10\ud83d\ude45\")\n        bot.reply(\n            to = message,\n            text = \"Good, you're going to jail alone! \u26d3\ud83e\uddd1\u26d3\",\n            replyMarkup = ReplyKeyboardRemove()\n        )\n    }\n\n    onUserShared { message: PrivateEventMessage<UserShared> ->\n        bot.reply(\n            to = message,\n            text = \"Haha, you and you friend are both going to jail! \u26d3\ud83d\udc6c\u26d3\",\n            replyMarkup = ReplyKeyboardRemove()\n        )\n    }\n\n    onChatShared { message: PrivateEventMessage<ChatShared> ->\n        bot.reply(\n            to = message,\n            text = \"Haha, now you're all going to jail! \u26d3\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66\u26d3\",\n            replyMarkup = ReplyKeyboardRemove()\n        )\n    }\n}.join()\n

Note

Read more about buildBehaviourWithLongPolling here

I hope you get the idea: the bot acts like a cop and asks the user to rat out his friends via a reply keyboard (it\u2019s an imaginary situation, of course). The user may refuse to cooperate, rat out a single friend or the whole imaginary group. The bot receives the user\u2019s choices as regular updates, the code above has explicit types (generally optional in Kotlin) and an assert to demonstrate this.

And here is how it works (the user selects the options in the order):

Note how you handle reply keyboards: you process regular messages. For instance, a simple text button sends a regular text message indistinguishable from a case when a user simply types the same text manually.

And don\u2019t be a rat in real life: remove the keyboards with the ReplyKeyboardRemove after you\u2019ve received the input! Otherwise, a keyboard will stay there indefinitely.

"},{"location":"tgbotapi/guides/keyboards.html#inline-keyboards","title":"Inline keyboards","text":"

Finally, to master the keyboards, you need to know how to handle the inline ones.

Again, let\u2019s explore the example. Imagine you\u2019re making a quiz where users are given a question and a set of answers. Additionally, users are given a link to the wiki page to help with the question and a Google button.

The quiz could be implemented this way:

// A simple data class to represent a question\nval question = Question(\n    image = \"https://upload.wikimedia.org/wikipedia/commons/a/a5/Tsunami_by_hokusai_19th_century.jpg\",\n    question = \"Who painted this?\",\n    answers = listOf(\n        Answer(\"Hokusai\", correct = true),\n        Answer(\"Sukenobu\"),\n        Answer(\"Ch\u014dshun\"),\n        Answer(\"Kiyonobu I\"),\n    ),\n    wiki = \"https://en.wikipedia.org/wiki/Ukiyo-e\",\n)\n\nbot.buildBehaviourWithLongPolling {\n    bot.sendPhoto(\n        chatId = chat,\n        fileId = InputFile.fromUrl(question.image),\n        text = question.question,\n        replyMarkup = inlineKeyboard {\n            // First row: answers\n            row {\n                for (answer in question.answers.shuffled()) {\n                    dataButton(\n                        text = answer.answer,\n                        data = \"${answer.answer}:${answer.correct}\",\n                    )\n                }\n            }\n\n            // Second row: help buttons\n            row {\n                urlButton(\"Wiki \ud83d\udc81\", question.wiki)\n                webAppButton(\"Google \ud83d\udd0d\", \"https://google.com\")\n            }\n        }\n    )\n\n    onDataCallbackQuery { callback: DataCallbackQuery ->\n        val (answer, correct) = callback.data.split(\":\")\n\n        if (correct.toBoolean()) {\n            bot.answerCallbackQuery(\n                callback,\n                text = \"$answer is a \u2705 correct answer!\",\n                showAlert = true\n            )\n        } else {\n            bot.answerCallbackQuery(\n                callback,\n                text = \"\u274c Try again, $answer is not a correct answer\u2026\",\n                showAlert = true\n            )\n        }\n    }\n}.join()\n

A few important things to note here.

First, the data buttons (they have the CallbackDataInlineKeyboardButton type, but in the code we used a neat DSL) must have unique data. If the data is not unique, Telegram clients will highlight all the buttons with the same data when a user clicks on one of them. Guess how I know that? Well, it\u2019s not in the docs, so trial and error is the only way to learn it (and many other things about the Telegram Bot API).

Second, the way you handle inline keyboards is different from the way you handle reply keyboards. Bot API will send updates with a callback_query field populated. This field, of a CallbackQuery type, represents incoming callbacks from callback buttons in inline keyboards. The library turns them into multiple callback types, like the DataCallbackQuery we used in the example. Finally, to handle these callbacks you could use onDataCallbackQuery. Alternatively, if you\u2019re not using any DSLs, you have to handle the CallbackQueryUpdate update type.

Third, the buttons got highlighted when a user clicks on them. When you\u2019re done with the callback, you need to answer it, by using the answerCallbackQuery function. Otherwise, the button will remain highlighted. Telegram clients will eventually remove the highlight, but it\u2019s still frustrating.

Finally, you could choose between two styles of acknowledgment: a simple toast-like message or a modal alert. The showAlert flag controls this behavior.

And here is the demo of the quiz:

"},{"location":"tgbotapi/guides/keyboards.html#conclusion","title":"Conclusion","text":"

Today we\u2019ve learned how to use keyboards in Telegram bots. There are two types of keyboards: reply and inline. Reply keyboards replace the device\u2019s keyboard and make clients send a message with the predefined content. Inline keyboards are buttons attached to messages. Clicking on them causes the client to send a callback to the bot. In both scenarios the bot receives an update of a corresponding type and has to acknowledge the keayboard interaction for the client to work properly.

"},{"location":"tgbotapi/introduction/before-any-bot-project.html","title":"Before any bot project","text":"

There are several places you need to visit for starting work with any Telegram Bot framework on any language:

Anyway, the most important link is How do I create a bot? inside of Telegram Bot API

"},{"location":"tgbotapi/introduction/before-any-bot-project.html#next-steps","title":"Next steps","text":""},{"location":"tgbotapi/introduction/first-bot.html","title":"First bot","text":"

Examples info

A lot of examples with using of Telegram Bot API you can find in this github repository

"},{"location":"tgbotapi/introduction/first-bot.html#the-most-simple-bot","title":"The most simple bot","text":"

The most simple bot will just print information about itself. All source code you can find in this repository. Our interest here will be concentrated on the next example part:

suspend fun main(vararg args: String) {\n  val botToken = args.first()\n  val bot = telegramBot(botToken)\n  println(bot.getMe())\n}\n

So, let\u2019s get understanding, about what is going on:

  1. suspend fun main(vararg args: String):
    • suspend required for making of requests inside of this function. For more info you can open official documentation for coroutins. In fact, suspend fun main is the same that fun main() = runBlocking {} from examples
  2. val botToken = args.first(): here we are just getting the bot token from first arguments of command line
  3. val bot = telegramBot(botToken) : inside of bot will be RequestsExecutor object which will be used for all requests in any project with this library
  4. println(bot.getMe()): here happens calling of getMe extension

As a result, we will see in the command line something like

ExtendedBot(id=ChatId(chatId=123456789), username=Username(username=@first_test_ee17e8_bot), firstName=Your bot name, lastName=, canJoinGroups=false, canReadAllGroupMessages=false, supportsInlineQueries=false)\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html","title":"Including in your project","text":"

There are three projects:

TelegramBotAPI

Also, there is an aggregator-version tgbotapi, which will automatically include all projects above. It is most recommended version due to the fact that it is including all necessary tools around TelegramBotAPI Core, but it is optionally due to the possible restrictions on the result methods count (for android) or bundle size

Examples

You can find full examples info in this repository. In this repository there full codes which are working in normal situation. Currently, there is only one exception when these examples could work incorrectly: you are living in the location where Telegram Bot API is unavailable. For solving this problem you can read Proxy setup part

"},{"location":"tgbotapi/introduction/including-in-your-project.html#notice-about-repository","title":"Notice about repository","text":"

To use this library, you will need to include Maven Central repository in your project

"},{"location":"tgbotapi/introduction/including-in-your-project.html#buildgradle","title":"build.gradle","text":"
mavenCentral()\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#pomxml","title":"pom.xml","text":"
<repository>\n  <id>central</id>\n  <name>mavenCentral</name>\n  <url>https://repo1.maven.org/maven2</url>\n</repository>\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#dev-channel","title":"Dev channel","text":"

Besides, there is developer versions repo. To use it in your project, add the repo in repositories section:

Gradle
maven {\n    url \"https://git.inmo.dev/api/packages/InsanusMokrassar/maven\"\n}\n
Maven
<repository>\n  <id>dev.inmo</id>\n  <name>InmoDev</name>\n  <url>https://git.inmo.dev/api/packages/InsanusMokrassar/maven</url>\n</repository>\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#telegrambotapi","title":"TelegramBotAPI","text":"

As tgbotapi_version variable in next snippets will be used variable with next last published version:

"},{"location":"tgbotapi/introduction/including-in-your-project.html#buildgradle_1","title":"build.gradle","text":"
implementation \"dev.inmo:tgbotapi:$tgbotapi_version\"\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#pomxml_1","title":"pom.xml","text":"
<dependency>\n    <groupId>dev.inmo</groupId>\n    <artifactId>tgbotapi</artifactId>\n    <version>${tgbotapi_version}</version>\n</dependency>\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#telegrambotapi-core","title":"TelegramBotAPI Core","text":"

As tgbotapi_version variable in next snippets will be used variable with next last published version:

"},{"location":"tgbotapi/introduction/including-in-your-project.html#buildgradle_2","title":"build.gradle","text":"
implementation \"dev.inmo:tgbotapi.core:$tgbotapi_version\"\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#pomxml_2","title":"pom.xml","text":"
<dependency>\n    <groupId>dev.inmo</groupId>\n    <artifactId>tgbotapi.core</artifactId>\n    <version>${tgbotapi_version}</version>\n</dependency>\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#telegrambotapi-api-extensions","title":"TelegramBotAPI API Extensions","text":"

As tgbotapi_version variable in next snippets will be used variable with next last published version:

"},{"location":"tgbotapi/introduction/including-in-your-project.html#buildgradle_3","title":"build.gradle","text":"
implementation \"dev.inmo:tgbotapi.api:$tgbotapi_version\"\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#pomxml_3","title":"pom.xml","text":"
<dependency>\n    <groupId>dev.inmo</groupId>\n    <artifactId>tgbotapi.api</artifactId>\n    <version>${tgbotapi_version}</version>\n</dependency>\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#telegrambotapi-utils-extensions","title":"TelegramBotAPI Utils Extensions","text":"

As tgbotapi_version variable in next snippets will be used variable with next last published version:

"},{"location":"tgbotapi/introduction/including-in-your-project.html#buildgradle_4","title":"build.gradle","text":"
implementation \"dev.inmo:tgbotapi.utils:$tgbotapi_version\"\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#pomxml_4","title":"pom.xml","text":"
<dependency>\n    <groupId>dev.inmo</groupId>\n    <artifactId>tgbotapi.utils</artifactId>\n    <version>${tgbotapi_version}</version>\n</dependency>\n
"},{"location":"tgbotapi/introduction/including-in-your-project.html#next-steps","title":"Next steps","text":""},{"location":"tgbotapi/introduction/proxy-setup.html","title":"Proxy setup","text":"

In some locations Telegram Bots API urls will be unavailable. In this case all examples will just throw exception like:

Exception in thread \"main\" java.net.ConnectException: Connection refused\n    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)\n    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)\n    at io.ktor.network.sockets.SocketImpl.connect$ktor_network(SocketImpl.kt:36)\n    at io.ktor.network.sockets.SocketImpl$connect$1.invokeSuspend(SocketImpl.kt)\n    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)\n    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)\n    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)\n    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:738)\n    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)\n    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)\n\nProcess finished with exit code 1\n

There are several ways to solve this problem:

"},{"location":"tgbotapi/introduction/proxy-setup.html#using-ktor-client-built-in-proxy","title":"Using Ktor Client built-in proxy","text":"

First of all, you will need to use one more library:

build.gradle:

implementation \"io.ktor:ktor-client-okhttp:2.3.5\"\n

Dependency note

In the snippet above was used version 2.3.5 which is actual for TelegramBotAPI at the moment of filling this documentation (october 11 2023, TelegramBotAPI version 9.2.2) and you can update version of this dependency in case if it is outdated.

For configuring proxy for your bot inside your program, you can use next snippet:

val botToken = \"HERE MUST BE YOUR TOKEN\" // (1)\nval bot = telegramBot(botToken) { // (2)\n    client = HttpClient(OkHttp) { // (3)\n        engine { // (4)\n            config { // (5)\n                proxy( // (6)\n                    Proxy( // (7)\n                        Proxy.Type.SOCKS, // (8)\n                        InetSocketAddress(\"127.0.0.1\", 1080) // (9)\n                    )\n                )\n            }\n        }\n    }\n}\n
  1. Here we are just creating variable botToken
  2. Start creating bot
  3. Setting HttpClient of our bot. On the time of documentation filling, OkHttp is one of the engines in Ktor system which supports socks proxy. More you can read on Ktor site in subparts about engines and proxy
  4. Start setting up of HttpClient engine
  5. Start setting up of HttpClient engine configuration
  6. Start setting up of proxy
  7. Creating proxy info object
  8. Saying that it is Socks proxy
  9. Creating address. Note that \"127.0.0.1\" and 1080 are configurable parameters
"},{"location":"tgbotapi/introduction/proxy-setup.html#more-complex-and-flexible-variant","title":"More complex and flexible variant","text":"

You may try to use custom engine for ktor. For example:

// JVM\n// OkHttp engine\n// Socks5 proxy\n\nval bot = telegramBot(botToken) { // (1)\n    val proxyHost = \"your proxy host\" // (2)\n    val proxyPort = 1080 //your proxy port // (3)\n    val username = \"proxy username\" // (4)\n    val password = \"proxy password\" // (5)\n\n    val proxyAddr = InetSocketAddress(proxyHost, proxyPort) // (6)\n    val proxy = Proxy(Proxy.Type.SOCKS, proxyAddr) // (7)\n\n    val passwordAuthentication = PasswordAuthentication(\n        username,\n        password.toCharArray()\n    ) // (8)\n    Authenticator.setDefault(object : Authenticator() { // (9)\n        override fun getPasswordAuthentication(): PasswordAuthentication? { // (10)\n            return if (requestingHost.lowercase() == proxyHost.lowercase()) { // (11)\n                passwordAuthentication\n            } else {\n                null\n            }\n        }\n    })\n    this.client = HttpClient(OkHttp) { // (12)\n        engine { // (13)\n            config { // (14)\n                proxy(proxy) // (15)\n            }\n        }\n    }\n}\n
  1. Start creating telegram bot
  2. Proxy host
  3. Proxy port
  4. Username for authentication. It is optional in case your proxy do not need auth
  5. Password for authentication. It is optional in case your proxy do not need auth
  6. Creating of proxy address for Proxy
  7. Proxy address and type information
  8. Proxy authentication info. It is optional in case your proxy do not need auth
  9. Setting up of authenticator. It is optional in case your proxy do not need auth
  10. Overriding of method that will return authentication info
  11. In case when request has been sent to the proxy (common request) - using authentication
  12. Creating of HttpClient and start configure it
  13. Start setup engine
  14. Start setup engine config
  15. Setting up of proxy information
"},{"location":"tgbotapi/introduction/proxy-setup.html#next-steps","title":"Next steps","text":""},{"location":"tgbotapi/logic/api-extensions.html","title":"API Extensions","text":"

API extensions is a module which you may include in your project in addition to core part. In most cases this module will allow just use syntax like bot.getUpdates() instead of bot.execute(GetUpdates()), but there are several other things you will achieve with that syntax.

"},{"location":"tgbotapi/logic/api-extensions.html#bot-builder","title":"Bot builder","text":"

This functionality allow you to build bot in more unified and comfortable way than standard creating with telegramBot function

buildBot(\n    \"TOKEN\"\n) {\n  proxy = ProxyBuilder.socks(host = \"127.0.0.1\", port = 4001) // just an example, more info on https://ktor.io/docs/proxy.html\n  ktorClientConfig = {\n    // configuring of ktor client\n  }\n  ktorClientEngineFactory = {\n   // configuring of ktor client engine \n  }\n}\n
"},{"location":"tgbotapi/logic/api-extensions.html#downloading-of-files","title":"Downloading of files","text":"

In standard library requests there are no way to download some file retrieved in updates or after requests. You may use syntax like bot.downloadFile(file) where file is TelegramMediaFile from telegram, FileId or even PathedFile from GetFile request (sources).

"},{"location":"tgbotapi/logic/api-extensions.html#live-location","title":"Live location","text":"

By default, you should handle updates of Live location by your code. But with extension bot#startLiveLocation you may provide all necessary startup parameters and handle updates with just calling updateLocation for retrieved LiveLocationProvider.

"},{"location":"tgbotapi/logic/api-extensions.html#what-is-next","title":"What is next?","text":"

There are several things you may read next:

"},{"location":"tgbotapi/logic/behaviour-builder-with-fsm.html","title":"Behaviour Builder with FSM","text":"

Behaviour builder with FSM is based on the MicroUtils FSM. There are several important things in FSM:

StatesMachine have two methods:

The most based way to create StatesMachine and register StateHandlers looks like in the next snippet:

buildFSM<TrafficLightState> {\n    strictlyOn<SomeState> {\n        // state handling\n    }\n}.start(CoroutineScope(...)).join()\n

Full example

You may find full example of FSM usage in the tests of FSM in MicroUtils

So, you must do next steps before you will launch your bot with FSM:

"},{"location":"tgbotapi/logic/behaviour-builder-with-fsm.html#bot-with-fsm","title":"Bot with FSM","text":"

There are several extensions for TelegramBot to create your bot with FSM:

All of them will take as an callback some object with type CustomBehaviourContextReceiver and will looks like in the next snippet:

telegramBotWithBehaviourAndFSMAndStartLongPolling<YourStateType>(\"BOT_TOKEN\") {\n    // here you may use any operations from BehaviourBuilder\n    // here you may use any operations from BehaviourContextWithFSMBuilder like strictlyOn and others\n}\n
"},{"location":"tgbotapi/logic/behaviour-builder-with-fsm.html#examples","title":"Examples","text":""},{"location":"tgbotapi/logic/behaviour-builder.html","title":"Behaviour Builder","text":"

In the previous pages about updates handling and was mentioned that currently in the most cases you should use Flows. So, there is an improvement for that system which hide direct work with flows and allow you to create more declarative logic of your bot.

"},{"location":"tgbotapi/logic/behaviour-builder.html#main-parts-of-behaviour-builder","title":"Main parts of Behaviour Builder","text":"

There are several things you should know for better understanding of behaviour builder:

"},{"location":"tgbotapi/logic/behaviour-builder.html#initialization","title":"Initialization","text":"

As was said above, there is buildBehaviour function which allow you set up your bot logic. Let\u2019s see an example:

val bot = telegramBot(\"TOKEN\")\n\nbot.buildBehaviour {\n  onCommand(\"start\") { // creating of trigger\n    val message = it\n    val content = message.content\n\n    reply(message, \"Ok, send me one photo\") // send text message with replying on incoming message\n\n    val photoContent = waitPhoto().first() // waitPhoto will return List, so, get first element\n\n    val photo = downloadFile(photoContent) // ByteArray of photo\n\n    // some logic with saving of photos\n  }\n}\n
"},{"location":"tgbotapi/logic/behaviour-builder.html#filters","title":"Filters","text":"

In most cases there are opportunity to filter some of messages before starting of main logic. Let\u2019s look at this using the example above:

val bot = telegramBot(\"TOKEN\")\n\nbot.buildBehaviour {\n  onCommand(\n    \"start\",\n    initialFilter = {\n      it.content.textSources.size == 1 // make sure that user has sent /start without any additions\n    }\n  ) {\n    // ...\n  }\n}\n

OR

val bot = telegramBot(\"TOKEN\")\n\nbot.buildBehaviour {\n  onCommand(\n    \"start\",\n    requireOnlyCommandInMessage = true // it is default, but you can overwrite it with `requireOnlyCommandInMessage = false`\n  ) {\n    // ...\n  }\n}\n
"},{"location":"tgbotapi/logic/behaviour-builder.html#long-polling","title":"Long polling","text":"

In case you wish to start long polling, you have two options:

More info

More info about updates retrieving you may read at the Long Polling and Webhooks articles

"},{"location":"tgbotapi/logic/behaviour-builder.html#long-polling-from-buildbehaviour","title":"Long polling from buildBehaviour","text":"

With prepared bot:

val bot = telegramBot(\"TOKEN\")\n\nbot.buildBehaviourWithLongPolling {\n    onCommand(\n        \"start\",\n        requireOnlyCommandInMessage = true // it is default, but you can overwrite it with `requireOnlyCommandInMessage = false`\n    ) {\n        // ...\n    }\n}\n

Without prepared bot:

telegramBotWithBehaviourAndLongPolling(\"TOKEN\") {\n    onCommand(\n        \"start\",\n        requireOnlyCommandInMessage = true // it is default, but you can overwrite it with `requireOnlyCommandInMessage = false`\n    ) {\n        // ...\n    }\n}\n
"},{"location":"tgbotapi/logic/behaviour-builder.html#long-polling-from-the-result-of-behaviour-building","title":"Long polling from the result of behaviour building","text":"
val bot = telegramBot(\"TOKEN\")\nval rootContext = bot.buildBehaviour {\n    onCommand(\n        \"start\",\n        requireOnlyCommandInMessage = true // it is default, but you can overwrite it with `requireOnlyCommandInMessage = false`\n    ) {\n        // ...\n    }\n}\n\nbot.longPolling(rootContext) // start listening updates\n
"},{"location":"tgbotapi/logic/exceptions-handling.html","title":"Exceptions handling","text":"

Unfortunatelly, exceptions handling in this library is a bit difficult in some places, but that have at least two reasons: flexibility and usability.

"},{"location":"tgbotapi/logic/exceptions-handling.html#in-place-handling","title":"\u201cIn place\u201d handling","text":"

In case you know, where exceptions are happening, you may use several tools for exceptions catching:

"},{"location":"tgbotapi/logic/exceptions-handling.html#catching-with-result","title":"Catching with result","text":"

If you prefer to receive Result objects instead of some weird callbacks, you may use the next syntax:

safelyWithResult {\n    // do something\n}.onSuccess { // will be called if everything is right\n    // handle success\n}.onFailure { // will be called if something went wrong\n    // handle error\n    it.printStackTrace()\n}.getOrThrow() // will return value or throw exception\n
"},{"location":"tgbotapi/logic/exceptions-handling.html#catching-with-callback","title":"Catching with callback","text":"

Also there is more simple (in some cases) way to handle exceptions with callbacks:

safely(\n  {\n      // handle error\n      it.printStackTrace()\n      null // return value\n  }\n) {\n    // do something\n}\n
"},{"location":"tgbotapi/logic/exceptions-handling.html#bonus-different-types-of-handling","title":"Bonus: different types of handling","text":"

There are two types of handling:

"},{"location":"tgbotapi/logic/exceptions-handling.html#global-exceptions-handling","title":"Global exceptions handling","text":"

The most simple way to configure exceptions handling is to change CoroutineContext when you are creating your CoroutineScope for bot processing:

val bot = telegramBot(\"TOKEN\")\n\nbot.buildBehaviour (\n    scope = scope,\n    defaultExceptionsHandler = {\n        it.printStackTrace()\n    }\n) {\n    // ...\n}\n

OR

val bot = telegramBotWithBehaviour (\n    \"TOKEN\",\n    scope = scope,\n    defaultExceptionsHandler = {\n        it.printStackTrace()\n    }\n) {\n    // ...\n}\n

Here we have used ContextSafelyExceptionHandler class. It will pass default handling of exceptions and will call the block in most cases when something inside of your bot logic has thrown exception.

"},{"location":"tgbotapi/logic/files-handling.html","title":"Files handling","text":"

According to the documentation there are several ways to work with files:

"},{"location":"tgbotapi/logic/files-handling.html#files-receiving","title":"Files receiving","text":"

There are several cases you may need in your app to work with files:

"},{"location":"tgbotapi/logic/files-handling.html#where-to-get-file-id-or-url","title":"Where to get File id or url?","text":"

The most simple way to send some file is to get file id and send it. You may get file id from any message with media. For example, if you have received some Message, you may use asCommonMessage conversation to be able to get its content and then convert it to some content with media. Full code here:

val message: Message;\n\nval fileId = message.asCommonMessage() ?.withContent<MediaContent>() ?.content ?.media ?.fileId;\n

WAT? O.o

In the code above we get some message, safely converted it to CommonMessage with asCommonMessage, then safely took its content via withContent<MediaContent>() ?.content and then just get its media file id.

"},{"location":"tgbotapi/logic/files-handling.html#download-files","title":"Download files","text":"

There are three ways to download files:

"},{"location":"tgbotapi/logic/files-handling.html#downloading-with-api-extensions","title":"Downloading with API extensions","text":""},{"location":"tgbotapi/logic/files-handling.html#files-jvmandroid","title":"Files (JVM/Android)","text":"
val bot: TelegramBot;\nval fileId: FileId;\nval outputFile: File;\n\nbot.downloadFile(fileId, outputFile)\n

See downloadFile extension docs in the JVM tab to get more available options

There is also way with saving of data into temporal file. That will allow you to do with data whatever you want without high requirements to memory or network connection:

val bot: TelegramBot;\nval fileId: FileId;\n\nval tempFile: File = bot.downloadFileToTemp(fileId)\n

See downloadFileToTemp extension docs to get more available options

"},{"location":"tgbotapi/logic/files-handling.html#byte-read-channel","title":"Byte read channel","text":"
val bot: TelegramBot;\nval fileId: FileId;\n\nval bytes: ByteReadChannelAllocator = bot.downloadFileStream(fileId)\n

See downloadFileStream extension docs to get more available options

"},{"location":"tgbotapi/logic/files-handling.html#byte-read-channel-allocator","title":"Byte read channel allocator","text":"
val bot: TelegramBot;\nval fileId: FileId;\n\nval bytes: ByteReadChannelAllocator = bot.downloadFileStreamAllocator(fileId)\n

See downloadFileStreamAllocator extension docs to get more available options

"},{"location":"tgbotapi/logic/files-handling.html#byte-arrays","title":"Byte arrays","text":"
val bot: TelegramBot;\nval fileId: FileId;\n\nval bytes: ByteArray = bot.downloadFile(fileId)\n

See downloadFile extension docs to get more available options

"},{"location":"tgbotapi/logic/files-handling.html#low-level-or-how-does-it-work","title":"Low level or how does it work?","text":"

You may download file with streams or with downloading into the memory first. On low level you should do several things. They are presented in next snippet:

val bot: TelegramBot;\nval fileId: FileId;\n\nval pathedFile: PathedFile = bot.execute(GetFile(fileId))\n\nval downloadedBytes: ByteArray = bot.execute(DownloadFile(pathedFile.filePath))\n

In the snippet above we are getting file PathedFile by its FileId and use it to download file bytes into memory using DownloadFile request.

You may use almost the same way but with byte read channel allocator:

val bot: TelegramBot;\nval fileId: FileId;\n\nval pathedFile: PathedFile = bot.execute(GetFile(fileId))\n\nval channelAllocator: ByteReadChannelAllocator = bot.execute(DownloadFileStream(pathedFile.filePath))\n\nval byteReadChannel: ByteReadChannel = channelAllocator()\n

And then you may look into ByteReadChannel docs to get more info about what you can do with that.

Several useful links

"},{"location":"tgbotapi/logic/files-handling.html#files-sending","title":"Files sending","text":"

Of course, in most cases you must be sure that file have correct type.

"},{"location":"tgbotapi/logic/files-handling.html#fileid-and-fileurl","title":"FileId and FileUrl","text":"

It is the most simple way to send any media in Telegram, but this way have several restrictions:

"},{"location":"tgbotapi/logic/files-handling.html#sending-via-file","title":"Sending via file","text":"

JS Restrictions

Sending via file is accessible from all supported platforms, but there is small note about JS - due to restrictions of work with streams and stream-like data (JS have no native support of files streaming) on this platform all the files will be loaded inside of RAM before the sending to the telegram services.

Sending via file is available throw the MultipartFile. There are several wayt to get it:

In most cases, sending via files looks like in the next snippet:

val file: File;\n\nbot.sendDocument(chatId, file.asMultipartFile())\n
"},{"location":"tgbotapi/logic/low-level-work-with-bots.html","title":"Low-level work with bots","text":"

The base version of library was done a lot of time ago and just got several additions related to improvements, updates in Telegram Bot API or some requests from our community.

"},{"location":"tgbotapi/logic/low-level-work-with-bots.html#base-things","title":"Base things","text":"

There are several important things in context of this library:

So, in most cases all your request calls with simplified api of this library (like bot.getMe()) will looks like bot.execute(GetMe). Result of these calls is defined in type of any request (for example, for GetMe request the result type is ExtendedBot). As a result, you can avoid any extension api (like special API extensions) and use low level request with full controlling of the whole logic flow.

"},{"location":"tgbotapi/logic/low-level-work-with-bots.html#how-to-handle-updates","title":"How to handle updates","text":"

As was written above, it will require some request:

val updates = bot.execute(GetUpdates())\n

Result type of GetUpdates request is Update. You may find inheritors of this interface in Update kdocs.

"},{"location":"tgbotapi/logic/low-level-work-with-bots.html#what-is-next","title":"What is next?","text":"

As was said above, you may look into our API extensions in case you wish to use more high-level functions instead of bot.execute(SomeRequest()). Besides, it will be very useful to know more about updates retrieving.

"},{"location":"tgbotapi/logic/media-groups.html","title":"Media Groups","text":"

As you know, Telegram have the feature named Media Groups. Media groups have several differences with the common messages:

"},{"location":"tgbotapi/logic/media-groups.html#specific-of-media-groups-in-libraries","title":"Specific of media groups in libraries","text":"

Row updates

In tgbotapi there is no any additional handling of media groups by default and in case you will use simple bot.getUpdates, you will get the list of row updates and media groups will be included in this list as separated messages with MediaGroupPartContent. In that case you may use convertWithMediaGroupUpdates to be able to work with media groups as will be described below

In case you are using standard long polling (one of alternatives is telegramBotWithBehaviourAndLongPolling) or webhooks updates will be converted uner the hood and as a result, you will take media groups as a content in one message:

telegramBotWithBehaviourAndLongPolling(\n  \"token\"\n) {\n  onVisualGallery { // it: CommonMessage<MediaGroupContent<VisualMediaGroupPartContent>>\n    it.content // MediaGroupContent<VisualMediaGroupPartContent>\n    it.content.group // List<MediaGroupCollectionContent.PartWrapper<VisualMediaGroupPartContent>>\n    it.content.group.forEach { // it: MediaGroupCollectionContent.PartWrapper<VisualMediaGroupPartContent>\n      it.messageId // source message id for current media group part\n      it.sourceMessage // source message for current media group part\n      it.content // VisualMediaGroupPartContent\n      println(it.content) // will print current content part info\n    }\n  }\n}\n

KDocs:

In two words, in difference with row Telegram Bot API, you will take media groups in one message instead of messages list.

"},{"location":"tgbotapi/logic/types-conversations.html","title":"Types conversations","text":"

One of the most important topics in context of tgbotapi is types conversations. This library is very strong-typed and a lot of things are based on types hierarchy. Lets look into the hierarchy of classes for the Message in 0.35.8:

As you may see, it is a little bit complex and require several tools for types conversation.

"},{"location":"tgbotapi/logic/types-conversations.html#as","title":"As","text":"

as conversations will return new type in case if it is possible. For example, when you got Message, you may use asContentMessage conversation to get message with content:

val message: Message;\nprintln(message.asContentMessage() ?.content)\n

This code will print null in case when message is not ContentMessage, and content when is.

"},{"location":"tgbotapi/logic/types-conversations.html#require","title":"Require","text":"

require works like as, but instead of returning nullable type, it will always return object with required type OR throw ClassCastException:

val message: Message;\nprintln(message.requireContentMessage().content)\n

This code will throw exception when message is not ContentMessage and print content when is.

"},{"location":"tgbotapi/logic/types-conversations.html#when","title":"When","text":"

when extensions will call passed block when type is correct. For example:

val message: Message;\nmessage.whenContentMessage {\n    println(it.content)\n}\n

Code placed above will print content when message is ContentMessage and do nothing when not

"},{"location":"tgbotapi/logic/updates-with-flows.html","title":"Updates with flows","text":"

Of course, in most cases here we will look up the way of using utils extnsions, but you may read deeper about updates retrieving here.

"},{"location":"tgbotapi/logic/updates-with-flows.html#phylosophy-of-flow-updates-retrieving","title":"Phylosophy of Flow updates retrieving","text":"

In most updates retrieving processes there are two components: UpdatesFiler and its inheritor FlowsUpdatesFilter. It is assumed, that you will do several things in your app to handle updates:

Let\u2019s look how it works with the factory above:

// Step 1 - create filter\nval filter = flowsUpdatesFilter {\n  // Step 2 - set up handling. In this case we will print any message from group or user in console\n  messageFlow.onEach {\n    println(it)\n  }.launchIn(someCoroutineScope)\n}\n\n// Step 3 - passing updates to filter\nbot.getUpdates().forEach {\n  filter.asUpdatesReceiver(it)\n}\n
"},{"location":"tgbotapi/logic/updates-with-flows.html#long-polling","title":"Long polling","text":"

Some example with long polling has been described above. But it is more useful to use some factories for it. In this page we will look for simple variant with TelegramBot#longPolling. So, with this function, your handling of updates will looks like:

val bot = telegramBot(\"TOKEN\")\n\nbot.longPolling {\n  messageFlow.onEach {\n    println(it)\n  }.launchIn(someCoroutineScope)\n}.join()\n

This example looks like the example above with three steps, but there are several important things here:

"},{"location":"tgbotapi/logic/updates-with-flows.html#results-and-what-is-next","title":"Results and What is next?","text":"

As a result you can start listen updates and react on it. Next recommended articles:

"},{"location":"tgbotapi/updates/heroku.html","title":"Heroku","text":"

Preview reading

It is recommended to visit our pages about UpdatesFilters and Webhooks to have more clear understanding about what is happening in this examples page

Heroku is a popular place for bots hosting. In common case you will need to configure webhooks for your server to include getting updates without problems. There are several things related to heroku you should know:

Server configuration alternatives

Here will be presented variants of configuration of webhooks and starting server. You always able to set webhook manualy, create your own ktor server and include webhooks handling in it or create and start server with only webhooks handling. More info you can get on page Webhooks

"},{"location":"tgbotapi/updates/heroku.html#short-example-with-behaviour-builder","title":"Short example with Behaviour Builder","text":"
suspend fun main {\n    // This subroute will be used as random webhook subroute to improve security according to the recommendations of Telegram\n    val subroute = uuid4().toString()\n    // Input/Output coroutines scope more info here: https://kotlinlang.org/docs/coroutines-guide.html\n    val scope = CoroutineScope(Dispatchers.IO)\n    // Here will be automatically created bot and available inside of lambda where you will setup your bot behaviour\n    telegramBotWithBehaviour(\n        // Pass TOKEN inside of your application environment variables\n        System.getenv(\"TOKEN\"),\n        scope = scope\n    ) {\n        // Set up webhooks and start to listen them\n        setWebhookInfoAndStartListenWebhooks(\n            // Automatic env which will be passed by heroku to the app\n            System.getenv(\"PORT\").toInt(),\n            // Server engine. More info here: https://ktor.io/docs/engines.html\n            Tomcat,\n            // Pass URL environment variable via settings of application. It must looks like https://<app name>.herokuapp.com\n            SetWebhook(\"${System.getenv(\"URL\").removeSuffix(\"/\")}/$subroute\"),\n            // Just callback which will be called when exceptions will happen inside of webhooks\n            {\n                it.printStackTrace()\n            },\n            // Set up listen requests from outside\n            \"0.0.0.0\",\n            // Set up subroute to listen webhooks to\n            subroute,\n            // BehaviourContext is the CoroutineScope and it is recommended to pass it inside of webhooks server\n            scope = this,\n            // BehaviourContext is the FlowsUpdatesFilter and it is recommended to pass its asUpdateReceiver as a block to retrieve all the updates\n            block = asUpdateReceiver\n        )\n        // Test reaction on each command with reply and text `Got it`\n        onUnhandledCommand {\n            reply(it, \"Got it\")\n        }\n    }\n    // Just potentially infinite await of bot completion\n    scope.coroutineContext.job.join()\n}\n
"},{"location":"tgbotapi/updates/heroku.html#configuration-example-without-behaviour-builder","title":"Configuration example without Behaviour Builder","text":"
// This subroute will be used as random webhook subroute to improve security according to the recommendations of Telegram\nval subroute = uuid4().toString()\nval bot = telegramBot(TOKEN)\nval scope = CoroutineScope(Dispatchers.Default)\n\nval filter = flowsUpdatesFilter {\n  messageFlow.onEach {\n    println(it) // will be printed \n  }.launchIn(scope)\n}\n\nval subroute = UUID.randomUUID().toString() // It will be used as subpath for security target as recommended by https://core.telegram.org/bots/api#setwebhook\n\nval server = bot.setWebhookInfoAndStartListenWebhooks(\n  // Automatic env which will be passed by heroku to the app\n  System.getenv(\"PORT\").toInt(),\n  // Server engine. More info here: https://ktor.io/docs/engines.html\n  Tomcat,\n  // Pass URL environment variable via settings of application. It must looks like https://<app name>.herokuapp.com\n  SetWebhook(\"${System.getenv(\"URL\").removeSuffix(\"/\")}/$subroute\"),\n  // Just callback which will be called when exceptions will happen inside of webhooks\n  {\n    it.printStackTrace()\n  },\n  // Set up listen requests from outside\n  \"0.0.0.0\",\n  // Set up subroute to listen webhooks to\n  subroute,\n  scope = scope,\n  block = filter.asUpdateReceiver\n)\n\nserver.environment.connectors.forEach {\n  println(it)\n}\nserver.start(false)\n
"},{"location":"tgbotapi/updates/long-polling.html","title":"Long polling","text":"

Long polling is a technology of getting updates for cases you do not have some dedicated server or you have no opportunity to receive updates via webhooks. More about this you can read in wiki.

"},{"location":"tgbotapi/updates/long-polling.html#related-topics","title":"Related topics","text":""},{"location":"tgbotapi/updates/long-polling.html#long-polling-in-this-library","title":"Long polling in this library","text":"

There are a lot of ways to include work with long polling:

"},{"location":"tgbotapi/updates/long-polling.html#longpolling","title":"longPolling","text":"

longPolling is a simple way to start getting updates and work with bot:

val bot = telegramBot(token)\nbot.longPolling(\n  textMessages().subscribe(scope) { // here \"scope\" is a CoroutineScope\n    println(it) // will be printed each update from chats with messages\n  }\n)\n
"},{"location":"tgbotapi/updates/long-polling.html#startgettingofupdatesbylongpolling","title":"startGettingOfUpdatesByLongPolling","text":"

The main aim of startGettingOfUpdatesByLongPolling extension was to provide more simple way to get updates in automatic mode:

val bot = telegramBot(token)\nbot.startGettingOfUpdatesByLongPolling(\n  {\n    println(it) // will be printed each update from chats with messages\n  }\n)\n

The other way is to use the most basic startGettingOfUpdatesByLongPolling extension:

val bot = telegramBot(token)\nbot.startGettingOfUpdatesByLongPolling {\n  println(it) // will be printed each update\n}\n
"},{"location":"tgbotapi/updates/long-polling.html#see-also","title":"See also","text":""},{"location":"tgbotapi/updates/updates-filters.html","title":"Updates filters","text":"

Due to the fact, that anyway you will get updates in one format (Update objects), some time ago was solved to create one point of updates filters for more usefull way of updates handling

"},{"location":"tgbotapi/updates/updates-filters.html#updatesfilter","title":"UpdatesFilter","text":"

UpdatesFilter currently have two properties:

Anyway, this filter can\u2019t work with updates by itself. For retrieving updates you should pass this filter to some of getting updates functions (long polling or webhooks).

"},{"location":"tgbotapi/updates/updates-filters.html#simpleupdatesfilter","title":"SimpleUpdatesFilter","text":"

SimpleUpdatesFilter is a simple variant of filters. It have a lot of UpdateReceiver properties which can be set up on creating of this object. For example, if you wish to get messages from chats (but not from channels), you can use next snippet:

SimpleUpdatesFilter {\n  println(it)\n}\n
"},{"location":"tgbotapi/updates/updates-filters.html#flowsupdatesfilter","title":"FlowsUpdatesFilter","text":"

A little bit more modern way is to use FlowsUpdatesFilter. It is very powerfull API of Kotlin Coroutines Flows, built-in support of additional extensions for FlowsUpdatesFilter and Flow<...> receivers and opportunity to split one filter for as much receivers as you want. Filter creating example:

val scope = CoroutineScope(Dispatchers.Default)\nflowsUpdatesFilter {\n  messageFlow.onEach {\n    println(it)\n  }.launchIn(scope)\n}\n
"},{"location":"tgbotapi/updates/updates-filters.html#combining-of-flows","title":"Combining of flows","text":"

In cases you need not separate logic for handling of messages from channels and chats there are three ways to combine different flows into one:

"},{"location":"tgbotapi/updates/updates-filters.html#types-filtering","title":"Types filtering","text":"

FlowsUpdatesFilter have a lot of extensions for messages types filtering:

flowsUpdatesFilter {\n  textMessages(scope).onEach {\n    println(it) // will be printed each message from channels and chats both with content only `TextContent`\n  }.launchIn(scope)\n}\n

The same things were created for media groups:

flowsUpdatesFilter {\n  mediaGroupMessages(scope).onEach {\n    println(it) // will be printed each media group messages list from both channels and chats without filtering of content\n  }.launchIn(scope)\n\n  mediaGroupPhotosMessages(scope).onEach {\n    println(it) // will be printed each media group messages list from both channels and chats with PhotoContent only\n  }.launchIn(scope)\n\n  mediaGroupVideosMessages(scope).onEach {\n    println(it) // will be printed each media group messages list from both channels and chats with VideoContent only\n  }.launchIn(scope)\n}\n

Besides, there is an opportunity to avoid separation on media groups and common messages and receive photos and videos content in one flow:

flowsUpdatesFilter {\n  sentMessagesWithMediaGroups(scope).onEach {\n    println(it) // will be printed each message including each separated media group message from both channels and chats without filtering of content\n  }.launchIn(scope)\n\n  photoMessagesWithMediaGroups(scope).onEach {\n    println(it) // will be printed each message including each separated media group message from both channels and chats with PhotoContent only\n  }.launchIn(scope)\n\n  videoMessagesWithMediaGroups(scope).onEach {\n    println(it) // will be printed each message including each separated media group message from both channels and chats with VideoContent only\n  }.launchIn(scope)\n}\n
"},{"location":"tgbotapi/updates/updates-filters.html#see-also","title":"See also","text":""},{"location":"tgbotapi/updates/webhooks.html","title":"Webhooks","text":"

In telegram bot API there is an opportunity to get updates via webhooks. In this case you will be able to retrieve updates without making additional requests. Most of currently available methods for webhooks are working on ktor server for JVM. Currently, next ways are available for using for webhooks:

"},{"location":"tgbotapi/updates/webhooks.html#setwebhookinfoandstartlistenwebhooks","title":"setWebhookInfoAndStartListenWebhooks","text":"

It is the most common way to set updates webhooks and start listening of them. Example:

val bot = telegramBot(TOKEN)\n\nval filter = flowsUpdatesFilter {\n  // ...\n}\n\nbot.setWebhookInfoAndStartListenWebhooks(\n  8080, // listening port. It is required for cases when your server hidden by some proxy or other system like Heroku\n  CIO, // default ktor server engine. It is recommended to replace it with something like `Netty`. More info about engines here: https://ktor.io/servers/configuration.html\n  SetWebhook(\n    \"address.com/webhook_route\",\n    File(\"/path/to/certificate\").toInputFile(), // certificate file. More info here: https://core.telegram.org/bots/webhooks#a-certificate-where-do-i-get-one-and-how\n    40, // max allowed updates, by default is null\n    filter.allowedUpdates\n  ),\n  {\n    it.printStackTrace() // optional handling of exceptions\n  },\n  \"0.0.0.0\", // listening host which will be used to bind by server\n  \"subroute\", // Optional subroute, if null - will listen root of address\n  WebhookPrivateKeyConfig( // optional config of private key. It will be installed in server to use TLS with custom certificate. More info here: https://core.telegram.org/bots/webhooks#a-certificate-where-do-i-get-one-and-how\n    \"/path/to/keystore.jks\",\n    \"KeystorePassword\",\n    \"Keystore key alias name\",\n    \"KeystoreAliasPassword\"\n  ),\n  scope, // Kotlin coroutine scope for internal transforming of media groups\n  filter.asUpdateReceiver\n)\n

If you will use previous example, ktor server will bind and listen url 0.0.0.0:8080/subroute and telegram will send requests to address address.com/webhook_route with custom certificate. Alternative variant will use the other SetWebhook request variant:

SetWebhook(\n  \"address.com/webhook_route\",\n  \"some_file_bot_id\".toInputFile(),\n  40, // max allowed updates, by default is null\n  filter.allowedUpdates\n)\n

As a result, request SetWebhook will be executed and after this server will start its working and handling of updates.

"},{"location":"tgbotapi/updates/webhooks.html#startlistenwebhooks","title":"startListenWebhooks","text":"

This function is working almost exactly like previous example, but this one will not set up webhook info in telegram:

val filter = flowsUpdatesFilter {\n  // ...\n}\n\nstartListenWebhooks(\n  8080, // listening port. It is required for cases when your server hidden by some proxy or other system like Heroku\n  CIO, // default ktor server engine. It is recommended to replace it with something like `Netty`. More info about engines here: https://ktor.io/servers/configuration.html\n  {\n    it.printStackTrace() // optional handling of exceptions\n  },\n  \"0.0.0.0\", // listening host which will be used to bind by server\n  \"subroute\", // Optional subroute, if null - will listen root of address\n  WebhookPrivateKeyConfig( // optional config of private key. It will be installed in server to use TLS with custom certificate. More info here: https://core.telegram.org/bots/webhooks#a-certificate-where-do-i-get-one-and-how\n    \"/path/to/keystore.jks\",\n    \"KeystorePassword\",\n    \"Keystore key alias name\",\n    \"KeystoreAliasPassword\"\n  ),\n  scope, // Kotlin coroutine scope for internal transforming of media groups\n  filter.asUpdateReceiver\n)\n

The result will be the same as in previous example: server will start its working and handling of updates on 0.0.0.0:8080/subroute. The difference here is that in case if this bot must not answer or send some requiests - it will not be necessary to create bot for receiving of updates.

"},{"location":"tgbotapi/updates/webhooks.html#extensions-includewebhookhandlinginroute-and-includewebhookhandlinginroutewithflows","title":"Extensions includeWebhookHandlingInRoute and includeWebhookHandlingInRouteWithFlows","text":"

For these extensions you will need to start your server manualy. In common case it will look like:

val scope = CoroutineScope(Dispatchers.Default)\n\nval filter = flowsUpdatesFilter {\n  // ...\n}\n\nval environment = applicationEngineEnvironment {\n  module {\n    routing {\n      includeWebhookHandlingInRoute(\n        scope,\n        {\n          it.printStackTrace()\n        },\n        filter.asUpdateReceiver\n      )\n    }\n  }\n  connector {\n    host = \"0.0.0.0\"\n    port = 8080\n  }\n}\n\nembeddedServer(CIO, environment).start(true) // will start server and wait its stoping\n

In the example above server will started and binded for listening on 0.0.0.0:8080.

"},{"location":"tgbotapi/updates/webhooks.html#see-also","title":"See also","text":""}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 8e0f856..dd6845b 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -2,232 +2,232 @@ https://docs.inmo.dev/index.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/krontab/index.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/krontab/describing/krontabscheduler.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/krontab/describing/string-format.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/krontab/introduction/faq.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/krontab/introduction/how-to-use.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/krontab/introduction/including-in-project.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/kslog/index.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/kslog/logging.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/kslog/setup.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/micro_utils/index.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/micro_utils/colors.ktstemplate.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/micro_utils/colors.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/micro_utils/resources.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/micro_utils/startup.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/micro_utils/repos/index.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/micro_utils/repos/inmemory.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/navigation/index.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/navigation/getting-started.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/plagubot/index.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/plagubot/opportunities_out_of_the_box.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/services/index.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/index.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/faq.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/logs.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/dsls/keyboards.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/dsls/live-location.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/dsls/text.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/guides/keyboards.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/introduction/before-any-bot-project.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/introduction/first-bot.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/introduction/including-in-your-project.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/introduction/proxy-setup.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/logic/api-extensions.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/logic/behaviour-builder-with-fsm.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/logic/behaviour-builder.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/logic/exceptions-handling.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/logic/files-handling.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/logic/low-level-work-with-bots.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/logic/media-groups.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/logic/types-conversations.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/logic/updates-with-flows.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/updates/heroku.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/updates/long-polling.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/updates/updates-filters.html - 2024-05-15 + 2024-05-29 daily https://docs.inmo.dev/tgbotapi/updates/webhooks.html - 2024-05-15 + 2024-05-29 daily \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 8f624153294b3a4786eed3257885ec9edda84823..c1014f2640feb06bd83af02c08ceed84f64de607 100644 GIT binary patch literal 664 zcmV;J0%!dniwFod1XpGP|8r?{Wo=<_E_iKh0M(hzj@uv*$M5?TQSR93s+GD`lD+i_ z+H-_qY|~)I%M5Y+_8sSAm92W{sRB!p9Wq8g4gdLoY+uiVU!5S5!?0U_sy6Et1cTOv zZnysV8E1(Lo_soSWxjw? zZPJ({-r!8cLt^JC-$j0eH0Uu>b!3vFJbKMg2yy0=5eQQ>kUc1|js*l$gb@n~sXOWb z1I9T=+MrLa)3>^rsYf3eJ78Wa`$ei?bEK8b*`)?KUw^(6;y9v2d~oc54w(3W?SXqZ zG?*ngK|DE0r1`p*JMpU?T>*rd?n2)Aq`9N40WC>}Kf>IgjxKU$7MKk z)|6dx7D`dThaGYQEk;l}%u0UFd5`>e{?<7y8x&WVNmF<4}v2Zw3 z%af7}0%19@rUHN)=%vqHl+h&TEkrdr?o~@eiSPw5!`Z;ND4UebZhfZ5Tz^ov&O=ea z9w+7D1YS)Tk5^HPK?xx_fOT4R5z|-#F3+P#!(dqcrn_``B~Yi)Y8LKmwiC7F4SmC{ ydx&^UMWA|=wqrz}eZsf{-z6crjv%9{>Pd;zO?h literal 664 zcmV;J0%!dniwFp?t3+l3|8r?{Wo=<_E_iKh0M(hzZrd;n$M1cLAa~hmu>#wWrnf!8 zb`E5Tw$;d@D^hX%_M`Jrq{9w74U&PtjzSARP=9_%*}k3zzdAxBhv8-YSZ&rT2nMYS z-OKvd&mZdR`gQlPP0i#87JfPh@ZJxfU&9i!Z7L)7P zotf!%=%9`8zO&l-d0XF&TxjYKoPP&9L=3E(`~fYHiLQ|qybUeuVv~nh2sUw)n`$u* zn)B8IN3_YXL{Hu7_hMLkoD`!<1jQh`V0>Egl5#c=GAQmH7fn zwMk=+c!M($_lcdSd>8p1(xAsk)qzQh^5``~A;g(eMj%YlK=z=-Iu;O25k@Q|q;9AK z3>fDeX@fqxPG9S0rXIax?0|Wx>}RQh&5>3zXO|k}eEs=Bh~tP7@xieJ+GFB9wtMbj z-(Z&D1o7x3k>=}K?!>QpbOjJ*x(oT>lje@H2DBs@{s41>I@$tIy*q*u<8vm>AD7|8 zSyOh&StvyTpLWO%v=~9@Fe~{v=RNY@`CAu>7xZ$FKOIWUvL7hV>jHe5Rkr)>`@-Q& zEl)}^2!!RpnhF4JpqD;(QAU%Tw-D9jxK}L=CBhfL3?~EQqHIz!yY-nKbNxZxIuAtw zdz_SqBX~7oJX}OA1|@{#0M=>MMNDG}xIB*{4TE9%o9^7@l|Y?Ft68`&*-q4wH}n;^ y?jhnK6@lte+Kv%@_6g$#e3OLaI)+$=9wumd#KV7rJ>R4i+x-S%)z;>i9{>Oj2~3gz diff --git a/tgbotapi/logic/behaviour-builder.html b/tgbotapi/logic/behaviour-builder.html index e4154ec..2b4bf43 100644 --- a/tgbotapi/logic/behaviour-builder.html +++ b/tgbotapi/logic/behaviour-builder.html @@ -1389,6 +1389,39 @@ + + +
  • + + + Long polling + + + + +
  • @@ -2404,6 +2437,39 @@ + + +
  • + + + Long polling + + + + +
  • @@ -2492,6 +2558,53 @@ } } +

    Long polling

    +

    In case you wish to start long polling, you have two options:

    +
      +
    • Start long polling with buildBehaviour additional functions
    • +
    • Start long polling from using the result of buildBehaviour
    • +
    +
    +

    More info

    +

    More info about updates retrieving you may read at the Long Polling and Webhooks +articles

    +
    +

    Long polling from buildBehaviour

    +

    With prepared bot:

    +
    val bot = telegramBot("TOKEN")
    +
    +bot.buildBehaviourWithLongPolling {
    +    onCommand(
    +        "start",
    +        requireOnlyCommandInMessage = true // it is default, but you can overwrite it with `requireOnlyCommandInMessage = false`
    +    ) {
    +        // ...
    +    }
    +}
    +
    +

    Without prepared bot:

    +
    telegramBotWithBehaviourAndLongPolling("TOKEN") {
    +    onCommand(
    +        "start",
    +        requireOnlyCommandInMessage = true // it is default, but you can overwrite it with `requireOnlyCommandInMessage = false`
    +    ) {
    +        // ...
    +    }
    +}
    +
    +

    Long polling from the result of behaviour building

    +
    val bot = telegramBot("TOKEN")
    +val rootContext = bot.buildBehaviour {
    +    onCommand(
    +        "start",
    +        requireOnlyCommandInMessage = true // it is default, but you can overwrite it with `requireOnlyCommandInMessage = false`
    +    ) {
    +        // ...
    +    }
    +}
    +
    +bot.longPolling(rootContext) // start listening updates
    +