mirror of
https://github.com/InsanusMokrassar/docs.git
synced 2024-11-26 03:58:55 +00:00
1 line
171 KiB
JSON
1 line
171 KiB
JSON
{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"index.html","title":"Insanus Mokrassar libraries home","text":"<p>Hello :) It is my libraries docs place and I glad to welcome you here. I hope, this documentation place will help you.</p>"},{"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":"<p>Library was created to give opportunity to launch some things from time to time according to some schedule in runtime of applications.</p>"},{"location":"krontab/index.html#how-to-use","title":"How to use","text":"<p>Here you may find the builder for <code>Krontab</code> templates creation.</p> <p>There are several ways to configure and use this library:</p> <ul> <li>From some string</li> <li>From builder</li> </ul> <p>Anyway, to start some action from time to time you will need to use one of extensions/functions:</p> <pre><code>val kronScheduler = /* creating of KronScheduler instance */;\n\nkronScheduler.doWhile {\n // some action\n true // true - repeat on next time\n}\n</code></pre>"},{"location":"krontab/index.html#including-in-project","title":"Including in project","text":"<p>If you want to include <code>krontab</code> in your project, just add next line to your dependencies part:</p> <pre><code>implementation \"dev.inmo:krontab:$krontab_version\"\n</code></pre> <p>Next version is the latest currently for the library:</p> <p></p> <p>For old version of Gradle, instead of <code>implementation</code> word developers must use <code>compile</code>.</p>"},{"location":"krontab/index.html#config-from-string","title":"Config from string","text":"<p>Developers can use more simple way to configure repeat times is string. String configuring like a <code>crontab</code>, but with a little bit different meanings:</p> <pre><code>/--------------- 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</code></pre> <p>It is different with original <code>crontab</code> 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:</p> <pre><code>doWhile(\"/5 * * * *\") {\n println(\"Called\")\n true // true - repeat on next time\n}\n</code></pre> <p>Another version:</p> <pre><code>doInfinity(\"/5 * * * *\") {\n println(\"Called\")\n}\n</code></pre> <p>Both of examples will print <code>Called</code> message every five seconds.</p>"},{"location":"krontab/index.html#config-via-builder","title":"Config via builder","text":"<p>Also, this library currently supports DSL for creating the same goals:</p> <pre><code>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</code></pre> <p>Or</p> <pre><code>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</code></pre> <p>Or</p> <pre><code>val kronScheduler = buildSchedule {\n seconds {\n 0 every 5\n }\n}\nkronScheduler.doInfinity {\n println(\"Called\")\n}\n</code></pre> <p>All of these examples will do the same things: print <code>Called</code> message every five seconds.</p>"},{"location":"krontab/index.html#do-functions","title":"do* functions","text":"<p>With regular <code>doOnce</code>/<code>doWhile</code>/<code>doInfinity</code> there are two types of their variations: local and timezoned. Local variations (<code>doOnceLocal</code>/<code>doWhileLocal</code>/<code>doInfinityLocal</code>) will pass <code>DateTime</code> as an argument into the block:</p> <pre><code>doInfinityLocal(\"/5 * * * *\") {\n println(it) // will print current date time\n}\n</code></pre> <p>Timezoned variations (<code>doOnceTz</code>/<code>doWhileTz</code>/<code>doInfinityTz</code>) will do the same thing but pass as an argument <code>DateTimeTz</code>:</p> <pre><code>doInfinityTz(\"/5 * * * * 0o\") {\n println(it) // will print current date time in UTC\n}\n</code></pre> <p>It is useful in cases when you need to get the time of calling and avoid extra calls to system time.</p>"},{"location":"krontab/index.html#helpful-table-for","title":"Helpful table for","text":"No args Local <code>DateTime</code> Local <code>DateTimeTz</code> with offset of <code>KronScheduler</code> Call only near time doOnce doOnceLocal doOnceTz Call while condition is true doWhile doWhileLocal doWhileTz Work infinity* doInfinity doInfinityLocal doInfinityTz <p>*Here there is an important notice, that <code>Work infinity</code> is not exactly <code>infinity</code>. Actually, that means that <code>do while coroutine is alive</code> and in fact executing will be stopped when coroutine became cancelled.</p>"},{"location":"krontab/index.html#kronscheduler-as-a-flow","title":"KronScheduler as a Flow","text":"<p>Any <code>KronScheduler</code> can be converted to a <code>Flow<DateTime></code> using extension <code>asFlow</code>:</p> <pre><code>val kronScheduler = buildSchedule {\n seconds {\n 0 every 1\n }\n}\n\nval flow = kronScheduler.asFlow()\n</code></pre> <p>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 <code>takeWhile</code>:</p> <pre><code>flow.takeWhile {\n condition()\n}.collect {\n action()\n}\n</code></pre>"},{"location":"krontab/index.html#offsets","title":"Offsets","text":"<p>Offsets in this library works via passing parameter ending with <code>o</code> in any place after <code>month</code> config. Currently, there is only one format supported for offsets: minutes of offsets. To use time zones you will need to call <code>next</code> method with <code>DateTimeTz</code> argument or <code>nextTimeZoned</code> method with any <code>KronScheduler</code> instance, but in case if this scheduler is not instance of <code>KronSchedulerTz</code> it will work like you passed just <code>DateTime</code>.</p> <p>Besides, in case you wish to use time zones explicitly, you will need to get <code>KronSchedulerTz</code>. It is possible by:</p> <ul> <li>Using <code>createSimpleScheduler</code>/<code>buildSchedule</code>/<code>KrontabTemplate#toSchedule</code>/<code>KrontabTemplate#toKronScheduler</code> methods with passing <code>defaultOffset</code> parameter</li> <li>Using <code>SchedulerBuilder#build</code>/<code>createSimpleScheduler</code>/<code>buildSchedule</code>/<code>KrontabTemplate#toSchedule</code>/<code>KrontabTemplate#toKronScheduler</code> methods with casting to <code>KronSchedulerTz</code> in case you are pretty sure that it is timezoned <code>KronScheduler</code></li> <li>Creating your own implementation of <code>KronSchedulerTz</code></li> </ul>"},{"location":"krontab/index.html#note-about-week-days","title":"Note about week days","text":"<p>Unlike original CRON, here week days:</p> <ul> <li>Works as <code>AND</code>: cron date time will search first day which will pass requirement according all parameters including week days</li> <li>You may use any related to numbers syntax with week days: <code>0-3w</code>, <code>0,1,2,3w</code>, etc.</li> <li>Week days (as well as years and offsets) are optional and can be placed anywhere after <code>month</code></li> </ul>"},{"location":"krontab/describing/krontabscheduler.html","title":"KrontabScheduler","text":"<p><code>KronScheduler</code> is the simple interface with only one function <code>next</code>. This function optionally get as a parameter <code>DateTime</code> which will be used as start point for the calculation of next trigger time. This function will return the next <code>DateTime</code> when something must happen.</p>"},{"location":"krontab/describing/krontabscheduler.html#default-realisation","title":"Default realisation","text":"<p>Default realisation (<code>CronDateTimeScheduler</code>) can be created using several ways:</p> <ul> <li>Via <code>buildSchedule</code> (or <code>createSimpleScheduler</code>) functions with crontab-like syntax parameter</li> <li>Via <code>buildSchedule</code> (or <code>SchedulerBuilder</code> object), which using lambda to configure scheduler</li> </ul> <p>In the examples below the result of created scheduler will be the same.</p>"},{"location":"krontab/describing/krontabscheduler.html#crontab-like-way","title":"Crontab-like way","text":"<p>Crontab-like syntax</p> <p> See String format for more info about the crontab-line syntax</p> <p>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):</p> <pre><code>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</code></pre>"},{"location":"krontab/describing/krontabscheduler.html#lambda-way","title":"Lambda way","text":"<p>In case of usage builder (lets call it <code>lambda way</code>), you will be able to configure scheduler in more type-safe way:</p> <pre><code>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</code></pre>"},{"location":"krontab/describing/krontabscheduler.html#custom-scheduler","title":"Custom scheduler","text":"<p>You are always able to use your own realisation of scheduler. For example:</p> <pre><code>class RandomScheduler : KronScheduler {\n override suspend fun next(relatively: DateTime): DateTime {\n return relatively + DateTimeSpan(seconds = Random.nextInt() % 60)\n }\n}\n</code></pre> <p>In the example above we have created <code>RandomScheduler</code>, which will return random next time in range <code>0-60</code> seconds since <code>relatively</code> argument.</p>"},{"location":"krontab/describing/string-format.html","title":"String format","text":"<p>As in <code>crontab</code> util, this library have almost the same format of string:</p> 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 <code>Int</code> Any <code>Int</code> 0..6 0..999 Suffix - - - - - - <code>o</code> <code>w</code> <code>ms</code> 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 <code>0</code>, <code>*/15</code>, <code>30</code> <code>0</code>, <code>*/15</code>, <code>30</code> <code>0</code>, <code>*/15</code>, <code>22</code> <code>0</code>, <code>*/15</code>, <code>30</code> <code>0</code>, <code>*/5</code>, <code>11</code> <code>0</code>, <code>*/15</code>, <code>30</code> <code>60o</code> (UTC+1) <code>0w</code>, <code>*/2w</code>, <code>4w</code> <code>0ms</code>, <code>*/150ms</code>, <code>300ms</code> <p>Example with almost same description:</p> <pre><code>/-------------------- (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</code></pre> <p>Years, timezone, week days and milliseconds are optional settings. Next snippets are equal:</p> <pre><code>*/15 * * * *\n*/15 * * * * * // with year\n*/15 * * * * * 0ms // with year and milliseconds\n</code></pre>"},{"location":"krontab/describing/string-format.html#supported-syntax","title":"Supported syntax","text":"<p>Currently the library support next syntax for date/time elements:</p> <ul> <li><code>{int}-{int}</code> - ranges</li> <li><code>{int}/{int}</code> - start/step</li> <li><code>*/{int}</code> - every {int}</li> <li><code>{int}</code> - just at the time</li> <li><code>{other_element},{other_element}</code> - listing</li> <li><code>F</code> or <code>f</code> - first possible value</li> <li><code>L</code> or <code>l</code> - last possible value (last day of month, for example)</li> </ul>"},{"location":"krontab/describing/string-format.html#ranges","title":"Ranges","text":"<p>Ranges are working like common <code>rangeTo</code> (or <code>..</code>) in kotlin:</p> <pre><code>0-5 * * * *\n</code></pre> <p>In the example above scheduler will trigger every second from the beginning of the minute up to fifth second of minute.</p>"},{"location":"krontab/describing/string-format.html#startstep","title":"Start/Step","text":"<p>Start/step is a little bit more complicated syntax. It means <code>start from the first element, repeat triggering every second element</code>. Examples:</p> <pre><code>5/15 * * * *\n</code></pre> <p>Means that each minute starting from fifth second it will repeat triggering every fifteenth second: <code>5, 20, 35, 50</code>.</p>"},{"location":"krontab/describing/string-format.html#every","title":"Every","text":"<p>Every is more simple syntax and could be explained as a shortcut for <code>0/{int}</code>. Example:</p> <pre><code>*/15 * * * *\n</code></pre> <p>Means that each minute it will repeat triggering every fifteenth second: <code>0, 15, 30, 45</code>.</p>"},{"location":"krontab/describing/string-format.html#just-at-the-time","title":"Just at the time","text":"<p>The most simple syntax. It means, that scheduler will call triggering every time when element was reached:</p> <pre><code>15 * * * *\n</code></pre> <p>Means that each minute scheduler will call triggering at the fifteenth second.</p>"},{"location":"krontab/describing/string-format.html#listing","title":"Listing","text":"<p>All the previous elements can be combined with listing. Lets just see several examples:</p> <pre><code>0,10 * * * *\n</code></pre> <p>Will trigger every minute at the <code>0</code> and <code>10</code> seconds (see Just at the time)</p> <pre><code>0-5,10 * * * *\n</code></pre> <p>Will trigger every minute from <code>0</code> to <code>5</code> seconds and at the <code>10</code> seconds (see Ranges)</p>"},{"location":"krontab/describing/string-format.html#examples","title":"Examples","text":"<ul> <li><code>0/5 * * * *</code> for every five seconds triggering</li> <li><code>0/5,L * * * *</code> for every five seconds triggering and on 59 second</li> <li><code>0/15 30 * * *</code> for every 15th seconds in a half of each hour</li> <li><code>0/15 30 * * * 500ms</code> for every 15th seconds in a half of each hour when milliseconds equal to 500</li> <li><code>1 2 3 F,4,L 5</code> for triggering in near first second of second minute of third hour of first, fifth and last days of may</li> <li><code>1 2 3 F,4,L 5 60o</code> for triggering in near first second of second minute of third hour of first, fifth and last days of may with timezone UTC+01:00</li> <li><code>1 2 3 F,4,L 5 60o 0-2w</code> for triggering in near first second of second minute of third hour of first, fifth and last days of may in case if it will be in Sunday-Tuesday week days with timezone UTC+01:00</li> <li><code>1 2 3 F,4,L 5 2021</code> for triggering in near first second of second minute of third hour of first, fifth and last days of may of 2021st year</li> <li><code>1 2 3 F,4,L 5 2021 60o</code> for triggering in near first second of second minute of third hour of first, fifth and last days of may of 2021st year with timezone UTC+01:00</li> <li><code>1 2 3 F,4,L 5 2021 60o 0-2w</code> for triggering in near first second of second minute of third hour of first, fifth and last days of may of 2021st year if it will be in Sunday-Tuesday week days with timezone UTC+01:00</li> <li><code>1 2 3 F,4,L 5 2021 60o 0-2w 500ms</code> for triggering in near first second of second minute of third hour of first, fifth and last days of may of 2021st year if it will be in Sunday-Tuesday week days with timezone UTC+01:00 when milliseconds will be equal to 500</li> </ul>"},{"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":"<p>Not very often. It depends on libraries (coroutines, korlibs/klock) updates and on some new awesome, but lightweight, features coming.</p>"},{"location":"krontab/introduction/faq.html#where-this-library-could-be-useful","title":"Where this library could be useful?","text":"<p>First of all, this library will be useful for long uptime applications which have some tasks to do from time to time.</p>"},{"location":"krontab/introduction/faq.html#how-to-use-crontab-like-syntax","title":"How to use crontab-like syntax?","text":"<p>In two words, you should call <code>buildSchedule</code> or <code>createSimpleScheduler</code>:</p> <pre><code>buildSchedule(\"5 * * * *\").asFlow().collect { /* do something */ }\n</code></pre> <p>You can read more about syntax in String format section.</p>"},{"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":"<ul> <li>Including in project</li> </ul>"},{"location":"krontab/introduction/how-to-use.html#buildschedule","title":"<code>buildSchedule</code>","text":"<p>Custom KronScheduler</p> <p>You are always may create your own scheduler. In this section will be presented different ways and examples around standard <code>CronDateTimeScheduler</code> builders <code>buildSchedule</code>. You can read about schedulers in KrontabScheduler</p> <p>Currently, <code>buildSchedule</code> is the recommended start point for every scheduler. Usually, it is look like:</p> <pre><code>val scheduler = buildSchedule(\"5 * * * *\")\n</code></pre> <p>Or:</p> <pre><code>val scheduler = buildSchedule {\n seconds {\n at(5)\n }\n}\n</code></pre> <p>On the top of any <code>KronScheduler</code> currently there are several groups of extensions:</p> <ul> <li>Executes</li> <li>Shortcuts</li> <li>Flows</li> </ul>"},{"location":"krontab/introduction/how-to-use.html#executes","title":"Executes","text":"<p>All executes are look like <code>do...</code>. All executes are described below:</p> <ul> <li><code>doOnce</code> - will get the next time for executing, delay until that time and call <code>block</code> with returning of the <code>block</code> result</li> <li><code>doWhile</code> - will call <code>doOnce</code> while it will return <code>true</code> (that means that <code>block</code> must return <code>true</code> if it expects that next call must happen). In two words: it will run while <code>block</code> returning <code>true</code></li> <li><code>doInfinity</code> - will call the <code>block</code> using <code>doWhile</code> with predefined returning <code>true</code>. In two words: it will call <code>block</code> while it do not throw error</li> </ul>"},{"location":"krontab/introduction/how-to-use.html#shortcuts","title":"Shortcuts","text":"<p>Shortcuts are the constants that are initializing in a lazy way to provide preset <code>KronScheduler</code>s. For more info about <code>KrontabScheduler</code> you can read its own page.</p> <ul> <li><code>AnyTimeScheduler</code> - will always return incoming <code>DateTime</code> as next</li> <li><code>Every*Scheduler</code> - return near * since the passed <code>relatively</code>:</li> <li><code>EverySecondScheduler</code> / <code>KronScheduler.everyMillisecond</code></li> <li><code>EverySecondScheduler</code> / <code>KronScheduler.everySecond</code></li> <li><code>EveryMinuteScheduler</code> / <code>KronScheduler.everyMinute</code></li> <li><code>EveryHourScheduler</code> / <code>KronScheduler.hourly</code></li> <li><code>EveryDayOfMonthScheduler</code> / <code>KronScheduler.daily</code></li> <li><code>EveryMonthScheduler</code> / <code>KronScheduler.monthly</code></li> <li><code>EveryYearScheduler</code> / <code>KronScheduler.annually</code></li> </ul>"},{"location":"krontab/introduction/how-to-use.html#flows","title":"Flows","text":"<p>Here currently there is only one extension for <code>KronScheduler</code>: <code>KronScheduler#asFlow</code>. As a result you will get <code>Flow<DateTime></code> (in fact <code>SchedulerFlow</code>) which will trigger next <code>emit</code> on each not null <code>next</code> <code>DateTime</code></p>"},{"location":"krontab/introduction/including-in-project.html","title":"Including in project","text":"<p>In two words, you must add dependency <code>dev.inmo:krontab:$krontab_version</code> to your project. The latest version presented by next badge:</p> <p></p>"},{"location":"krontab/introduction/including-in-project.html#notice-about-repository","title":"Notice about repository","text":"<p>To use this library, you will need to include <code>MavenCentral</code> repository in you project</p>"},{"location":"krontab/introduction/including-in-project.html#buildgradle","title":"build.gradle","text":"<pre><code>mavenCentral()\n</code></pre>"},{"location":"krontab/introduction/including-in-project.html#dependencies","title":"Dependencies","text":"<p>Next snippets must be placed into your <code>dependencies</code> part of <code>build.gradle</code> (for gradle) or <code>pom.xml</code> (for maven).</p>"},{"location":"krontab/introduction/including-in-project.html#gradle","title":"Gradle","text":"<pre><code>implementation \"dev.inmo:krontab:$krontab_version\"\n</code></pre>"},{"location":"krontab/introduction/including-in-project.html#maven","title":"Maven","text":"<pre><code><dependency>\n <groupId>dev.inmo</groupId>\n <artifactId>krontab</artifactId>\n <version>${krontab_version}</version>\n</dependency>\n</code></pre>"},{"location":"kslog/index.html","title":"KSLog","text":"<p>It is simple and easy-to-use tool for logging on the most popular platforms in Kotlin Multiplatform:</p> <p> </p> <p></p> <p>By default, KSLog is using built-in tools for logging on each supported platform:</p> <ul> <li><code>java.util.logging.Logger</code> for <code>JVM</code></li> <li><code>android.util.Log</code> for <code>Android</code></li> <li><code>Console</code> for <code>JS</code></li> </ul> <p>But you always may create your logger and customize as you wish:</p> <pre><code>KSLog.default = KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->\n // do your logging\n}\n</code></pre> <p>This library also supports native targets in experimental mode. By default, all native targets will use simple printing in the console</p>"},{"location":"kslog/index.html#how-to-use","title":"How to use","text":""},{"location":"kslog/index.html#fast-travel","title":"Fast-travel","text":"<p>Just use some boring extensions like:</p> <pre><code>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</code></pre>"},{"location":"kslog/index.html#a-little-bit-deeper","title":"A little bit deeper","text":"<p>There are several important \u201cterms\u201d in context of this library:</p> <ul> <li>Default logger (available via <code>KSLog.default</code> or simply <code>KSLog</code>)</li> <li>Local logger (can be created via <code>KSLog</code> functions and passed anywhere as <code>KSLog</code>)</li> <li>Logging shortcuts like <code>KSLog.i</code>/<code>KSLog.info</code></li> <li>Built-in extension <code>Any.logger</code> which allow you to create logger binded to the default with the tag based on the class of receiver<ul> <li>Be careful with the receivers: if you will use some extension like <code>apply</code>, the receiver will be different with your class inside of that <code>apply</code></li> </ul> </li> </ul> <p>Every logging extension (like <code>KSLog.i</code>) have its analog with lazy inited message text and the same one with suffix <code>S</code> (like <code>KSLog.iS</code>) for the suspendable message calculation.</p> <p>Default logger can be created by passing <code>defaultTag</code> and one of variants log level filters: set or minimal loggable level. In <code>JVM</code> you also may setup any logger as base logger for default realizations of <code>KSLog</code>. Besides, you may use your own callback (on any target platform) as output of logging:</p> <pre><code>val logger = KSLog { logLevel, optionalTag, message, optionalThrowable ->\n println(\"[$logLevel] $optionalTag - $message: $optionalThrowable.stackTraceToString()\")\n}\n</code></pre> <p>In the example above we will take the <code>logger</code> which will just print incoming data as common output.</p>"},{"location":"kslog/index.html#installation","title":"Installation","text":""},{"location":"kslog/index.html#gradle","title":"Gradle","text":"<pre><code>implementation \"dev.inmo:kslog:$kslog_version\"\n</code></pre>"},{"location":"kslog/index.html#maven","title":"Maven","text":"<pre><code><dependency>\n <groupId>dev.inmo</groupId>\n <artifactId>kslog</artifactId>\n <version>${kslog_version}</version>\n</dependency>\n</code></pre>"},{"location":"kslog/logging.html","title":"Logging","text":"<p>Message type notice</p> <p> On this page all the messages will be just simple <code>String</code>, but you may pass any object as the message</p> <p>As has been said in the setup section, this library contains next levels of logging with their default representations on each platform:</p> 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 <p>Each of these levels have fullname and shortname shortcat extensions:</p> <ul> <li><code>KSLog.trace</code>/<code>KSLog.t</code>/<code>KSLog.tS</code></li> <li><code>KSLog.debug</code>/<code>KSLog.d</code>/<code>KSLog.dS</code></li> <li><code>KSLog.verbose</code>/<code>KSLog.v</code>/<code>KSLog.vS</code></li> <li><code>KSLog.info</code>/<code>KSLog.i</code>/<code>KSLog.iS</code></li> <li><code>KSLog.warning</code>/<code>KSLog.w</code>/<code>KSLog.wS</code></li> <li><code>KSLog.error</code>/<code>KSLog.e</code>/<code>KSLog.eS</code></li> <li><code>KSLog.assert</code>/<code>KSLog.wtf</code>/<code>KSLog.wtfS</code></li> </ul> <p>And any of these shortcuts may accept one of several arguments combinations:</p> <ul> <li>Tag (Optional), Throwable (Optional), Message Builder (simple inline callback for lazy creating of log message). This type of arguments is duplicated with <code>S</code> suffix for <code>suspendable</code> messages creating, for example</li> <li>Message, Throwable (Optional)</li> <li>Tag, Message, Throwable (Optional)</li> </ul> <p>So, when you want to log some expected exception, there are three common ways to do it:</p> <pre><code>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</code></pre> <p>Of course, any of this calls can be shortenned:</p> <pre><code>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</code></pre> <p>There is special shortcat - for base <code>performLog</code>. In that case the only change is that you will require to pass the <code>LogLevel</code> more obviously:</p> <pre><code>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</code></pre> <p>OR</p> <pre><code>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</code></pre>"},{"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":"<pre><code>implementation \"dev.inmo:kslog:$kslog_version\"\n</code></pre>"},{"location":"kslog/setup.html#gradle-kotlin-script","title":"Gradle (Kotlin Script)","text":"<pre><code>implementation(\"dev.inmo:kslog:$kslog_version\")\n</code></pre>"},{"location":"kslog/setup.html#maven-pom","title":"Maven (pom)","text":"<pre><code><dependency>\n <groupId>dev.inmo</groupId>\n <artifactId>kslog</artifactId>\n <version>${kslog_version}</version>\n</dependency>\n</code></pre>"},{"location":"kslog/setup.html#setup-in-code","title":"Setup in code","text":"<p>The main point in setup in your code is to setup default logger:</p> <pre><code>KSLog.default = KSLog(\"defaultTag\")\n</code></pre> <p>You may use custom <code>messageFormatter</code> in any of <code>KSLog</code> factory to customize output of <code>KSLog</code> logging. For example:</p> <pre><code>KSLog(\n \"loggingWithCustomFormat\",\n messageFormatter = { level, tag, message, throwable ->\n println(\"[$level] $tag - $message: $throwable\")\n }\n)\n</code></pre> <p>Additionally you may use one of several different settings:</p> <ul> <li><code>minLoggingLevel</code> - minimal logging level for the log which will be logged. The order of log level is next:<ul> <li>TRACE</li> <li>DEBUG</li> <li>VERBOSE</li> <li>INFO</li> <li>WARNING</li> <li>ERROR</li> <li>ASSERT</li> </ul> </li> <li><code>levels</code> - and iterable with the levels which should be logged</li> <li><code>firstLevel</code>,<code>secondLevel</code>,<code>otherLevels</code> - as <code>levels</code>, but <code>vararg</code> :)</li> </ul> <p>In case you are passing <code>minLoggingLevel</code>, the level and more important levels will be passed to logs. For example, when you are settings up your logger as in next snippet:</p> <pre><code>val logger = KSLog(\n \"exampleTag\",\n minLoggingLevel = LogLevel.INFO\n)\n</code></pre> <p>The next levels will be logged with <code>logger</code>:</p> <ul> <li><code>INFO</code></li> <li><code>WARNING</code></li> <li><code>ERROR</code></li> <li><code>ASSERT</code></li> </ul>"},{"location":"kslog/setup.html#special-loggers","title":"Special loggers","text":""},{"location":"kslog/setup.html#callbackkslog","title":"CallbackKSLog","text":"<p>It is logger which will call incoming <code>performLogCallback</code> on each logging. This logger can be create simply with one callback:</p> <pre><code>KSLog { level, tag, message, throwable ->\n println(\"[$level] $tag - $message: $throwable\")\n}\n</code></pre>"},{"location":"kslog/setup.html#taglogger","title":"TagLogger","text":"<p>It is simple value class which can be used for zero-cost usage of some tag and calling for <code>KSLog.default</code>. For example, if you will create tag logger with next code:</p> <pre><code>val logger = TagLogger(\"tagLoggerTag\")\n</code></pre> <p>The <code>logger</code> will call <code>KSLog.default</code> with the tag <code>tagLoggerTag</code> on each calling of logging.</p>"},{"location":"kslog/setup.html#filterkslog","title":"FilterKSLog","text":"<p>This pretty simple logger will call its <code>fallbackLogger</code> only in cases when incoming <code>messageFilter</code> will return true for logging:</p> <pre><code>val baseLogger = KSLog(\"base\") // log everything with the tag `base` if not set other\nval filtered = baseLogger.filtered { _, t, _ ->\n t == \"base\"\n}\n</code></pre> <p>In the example above <code>baseLogger</code> will perform logs in two ways: when it has been called directly or when we call log performing with the tag <code>\"base\"</code> or <code>null</code>. Besides, you can see there extension <code>filtered</code> which allow to create <code>FilterKSLog</code> logger with simple lambda.</p>"},{"location":"kslog/setup.html#typedkslog","title":"TypedKSLog","text":"<p>This logger accepts map of types with the target loggers. You may build this logger with the special simple DSL:</p> <pre><code>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</code></pre>"},{"location":"kslog/setup.html#automatical-loggers","title":"Automatical loggers","text":"<p>There are two things which can be useful in your code: <code>logger</code> and <code>logTag</code> extensions. <code>logTag</code> is the autocalculated by your object classname tag. <code>logger</code> extension can be used with applying to any object like in the next snippet:</p> <pre><code>class SomeClass {\n init {\n logger.i(\"inited\")\n }\n}\n</code></pre> <p>The code above will trigger calling of logging in <code>KSLog.default</code> with level <code>LogLevel.INFO</code> using tag <code>SomeClass</code> and message <code>\"inited\"</code>. As you could have guessed, <code>logger</code> is using <code>TagLogger</code> with <code>logTag</code> underhood and the most expensive operation here is automatical calculation of <code>logTag</code>.</p> <ul> <li>Extension <code>logger</code></li> </ul>"},{"location":"kslog/setup.html#jvm-specific-setup","title":"JVM specific setup","text":"<p>For JVM you may setup additionally use java loggers as the second parameter of <code>KSLog</code> factory. For example:</p> <pre><code>KSLog(\n \"yourTag\"\n Logger.getLogger(\"YourJavaLoggerName\")\n)\n</code></pre>"},{"location":"micro_utils/index.html","title":"MicroUtils","text":"<p><code>MicroUtils</code> is a set of libraries to help me (and, I hope, you too) in some routine doings of coding.</p> <p>First of all, this library collection is oriented to use next technologies:</p> <ul> <li><code>Kotlin Coroutines</code></li> <li><code>Kotlin Serialization</code></li> <li><code>Kotlin Exposed</code></li> <li><code>Ktor</code></li> <li><code>Koin</code></li> <li><code>Korlibs</code></li> </ul> <p>Warning</p> <p> 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</p>"},{"location":"micro_utils/colors.ktstemplate.html","title":"Colors.ktstemplate","text":"<p>group=dev.inmo artifact=micro_utils.colors.common package=$group.$artifact central_package=$group/$artifact</p>"},{"location":"micro_utils/colors.ktstemplate.html#colors","title":"Colors","text":"<ul> <li><code>Group</code>: <code>$group</code></li> <li><code>ArtifactId</code>: <code>$artifact</code></li> </ul> <p>Adding dependency:</p> <pre><code>implementation \"$group:$artifact:latest\"\n</code></pre> <p>Info</p> <p> All the samples below will represent <code>HEXAColor</code> with <code>r==0xaa</code>, <code>g==0xff</code>, <code>b==0x00</code> and <code>a==0xff</code></p> <p>This package contains mainly one file: HEXAColor. This file contains unified color with HEXA format. It consumes <code>UInt</code> by default constructor and r/g/b/a parameters in other main constructors:</p> <pre><code>HEXAColor(0xaaff00ffu) // 0xRGBAu as UInt\nHEXAColor(r = 0xaa, g = 0xff, b = 0x00, a = 0xff)\nHEXAColor(r = 0xaa, g = 0xff, b = 0x00, aOfOne = 1f)\n</code></pre> <p>Besides, you may use one of converters:</p> <pre><code>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</code></pre>"},{"location":"micro_utils/colors.html","title":"Colors","text":"<ul> <li><code>Group</code>: <code>dev.inmo</code></li> <li><code>ArtifactId</code>: <code>micro_utils.colors.common</code></li> </ul> <p>Adding dependency:</p> <pre><code>implementation \"dev.inmo:micro_utils.colors.common:latest\"\n</code></pre> <p>Info</p> <p> All the samples below will represent <code>HEXAColor</code> with <code>r==0xaa</code>, <code>g==0xff</code>, <code>b==0x00</code> and <code>a==0xff</code></p> <p>This package contains mainly one file: HEXAColor. This file contains unified color with HEXA format. It consumes <code>UInt</code> by default constructor and r/g/b/a parameters in other main constructors:</p> <pre><code>HEXAColor(0xaaff00ffu) // 0xRGBAu as UInt\nHEXAColor(r = 0xaa, g = 0xff, b = 0x00, a = 0xff)\nHEXAColor(r = 0xaa, g = 0xff, b = 0x00, aOfOne = 1f)\n</code></pre> <p>Besides, you may use one of converters:</p> <pre><code>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</code></pre>"},{"location":"micro_utils/resources.html","title":"Resources","text":"<p>Package: <code>dev.inmo:micro_utils.resources</code></p> <p>This package aimed to make some multiplatform support for resources of your application. As for now, there is only support for strings. Sample:</p> <pre><code>object Translations {\n val someVariable = buildStringResource(\n \"Sample default string\"\n ) {\n IetfLang.German variant lazy \"Beispiel f\u00fcr eine Standardzeichenkette\"\n }\n}\n</code></pre> <p>In this case, you will be able to use it with next logic:</p> <pre><code>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</code></pre>"},{"location":"micro_utils/resources.html#additional-opportunities-on-android-platform","title":"Additional opportunities on Android platform","text":"<p>On Android you may use <code>Configuration</code> (as well as <code>Resources</code> or <code>Context</code>) to get translation for current locale. For example:</p> <pre><code>val context: Context = // context retrieving\n\ncontext.translation(Translation.someVariable)\n</code></pre>"},{"location":"micro_utils/resources.html#additional-opportunities-on-jvm-platform","title":"Additional opportunities on JVM platform","text":"<p>On JVM platform you usually may use <code>Locale.getDefault()</code> to get <code>Locale</code> object and pass it to <code>translation</code> extension:</p> <pre><code>Translation.someVariable.translation(Locale.getDefault())\nTranslation.someVariable.translation() // Locale.getDefault() hidden\n</code></pre>"},{"location":"micro_utils/startup.html","title":"Startup","text":"<ul> <li>Plugins Package: <code>dev.inmo:micro_utils.startup.plugin</code></li> <li>Launcher Package: <code>dev.inmo:micro_utils.startup.launcher</code></li> </ul> <p>This package contains unified simple <code>Plugin</code>/<code>Launcher</code> tools for separating of your apps parts</p> <p>Launching logic:</p> flowchart TB StartLauncherPlugin.startAsync StartLauncherPlugin.startAsync --> KoinInit[\"Koin.init\"] KoinInit --> StartLauncherPlugin.setupDI subgraph StartLauncherPlugin.setupDI direction LR AddDefaultDependencies[\"Default dependencies: config as JsonObject, config as object, CoroutineScope, Json\"] SubPluginsSetupDI[\"Calling setupDI in subplugins\"] AddDefaultDependencies --> SubPluginsSetupDI end StartLauncherPlugin.setupDI --> startKoin startKoin --> StartLauncherPlugin.startPlugin subgraph StartLauncherPlugin.startPlugin direction LR LaunchSubplugins[\"Asynchronously (in CoroutineScope from Koin) start subplugins\"] end StartLauncherPlugin.startPlugin --> ReturnKoinAppAndLaunchJob[\"Return koinApp and laucnhing job\"]"},{"location":"micro_utils/startup.html#plugin","title":"Plugin","text":"<p>To define plugin, you must use <code>StartPlugin</code> as supertype for your plugin. Restrictions are simple: plugins must be an <code>object</code> or <code>class</code> with empty constructor. Basic sample is here:</p> <pre><code>object YourPlugin : StartPlugin {\n // Body of your plugin\n}\n</code></pre> <p>Each plugin may contains to parts:</p> <ul> <li><code>setupDI</code> function to set up DI part</li> <li><code>startPlugin</code> function to start plugin</li> </ul> <pre><code>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</code></pre>"},{"location":"micro_utils/startup.html#launcher","title":"Launcher","text":"<p>Basically, launcher module can be used to start application directly from <code>gradle</code>. Let\u2019s imagine you have this gradle groovy config:</p> <pre><code>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</code></pre> <p>You will be able to run your project with gradle command <code>./gradlew run --args=\"path/to/config.json\"</code>. <code>config.json</code> must contains something like:</p> <pre><code>{\n \"plugins\": [\n \"dev.inmo.micro_utils.startup.launcher.HelloWorldPlugin\"\n ]\n}\n</code></pre> <p>In current case you will see in logger different logs about launching including log from <code>HelloWorldPlugin</code> with text <code>Hello world</code>.</p>"},{"location":"micro_utils/repos/index.html","title":"Repos","text":"<p>Repositories in this library are unified interfaces to work with different types of standard repos:</p> <ul> <li>CRUD (create/read/update/delete)</li> <li>Key-value</li> <li>Key-values</li> </ul>"},{"location":"micro_utils/repos/index.html#crud","title":"CRUD","text":"<p>Default interface for any <code>CRUD</code>-oriented realization of repositories. This type of repos separated to three interfaces:</p> <ul> <li>ReadCRUDRepo</li> <li>WriteCRUDRepo</li> <li>CRUDRepo</li> </ul> flowchart TB ReadCRUDRepo --> CRUDRepo WriteCRUDRepo --> CRUDRepo <p><code>CRUDRepo</code> extends both <code>ReadCRUDRepo</code> and <code>WriteCRUDRepo</code>.</p> <p>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.</p>"},{"location":"micro_utils/repos/index.html#readcrudrepo","title":"<code>ReadCRUDRepo</code>","text":"<p>Contains read-only operations, such as getById, contains. This interface can\u2019t be observed because of it does not suppose any mutable operation.</p>"},{"location":"micro_utils/repos/index.html#writecrudrepo","title":"<code>WriteCRUDRepo</code>","text":"<p>Contains write-only operations, such as create, update. This interface can be observed via its flows:</p> <ul> <li>newObjectsFlow for newely created objects</li> <li>updatedObjectsFlow for old updated objects</li> <li>deletedObjectsIdsFlow for deleted objects</li> </ul> <p>Info</p> <p> By default, all mutating operations consumes <code>List</code>s of data (<code>List<New></code> for <code>create</code>, <code>List<Pair<Id, New>></code> for <code>update</code> and <code>List<Id></code> for delete), but all they have their extension function-variations with one/two args (like <code>create</code> with <code>New</code> arg)</p> <ul> <li><code>create</code> operation consumes list of <code>New</code> variants of object and produces <code>Registered</code>s list. In most cases, <code>Registered</code> variant of object should have <code>Id</code> of registered object, but it is not required for repo.</li> <li><code>update</code> operation consumes list of pairs with <code>Id</code> and <code>New</code> objects and produces list of <code>Registered</code> objects.</li> <li><code>deleteById</code> operation consumes list of <code>Id</code>s and do not consume anything except of notifying via <code>deletedObjectsIdsFlow</code>.</li> </ul>"},{"location":"micro_utils/repos/index.html#keyvalue","title":"KeyValue","text":"<p>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</p>"},{"location":"micro_utils/repos/index.html#readkeyvaluerepo","title":"ReadKeyValueRepo","text":"<p>Read repo provides functions like: contains, get or values.</p>"},{"location":"micro_utils/repos/index.html#writekeyvaluerepo","title":"WritekeyValueRepo","text":"<p>Contains write-only operations. This interface can be observed via its flows:</p> <ul> <li>onNewValue to retrieve newely set values and keys</li> <li>onValueRemoved for the values removed from repo</li> </ul> <p>Info</p> <p> By default, all mutating operations consumes some collections. For example, set require <code>Map</code> with <code>Key</code>s and <code>Value</code>s and do not returns anything. Instead, it will throw notification via <code>onNewValue</code> flow</p> <p>All the methods on <code>WriteKeyValueRepo</code> have their variances with <code>pairs</code> (for set) or plain <code>vararg</code>s.</p> <ul> <li><code>set</code> operation consumes map of <code>Key</code>s and their <code>Value</code>s, set them and produces updates via <code>onNewValue</code></li> <li><code>unset</code> operation consumes list of <code>Key</code>s, removing <code>Value</code> by <code>Key</code> and produces updates via <code>onValueRemoved</code></li> <li><code>unsetWithValues</code> consumes list of <code>Value</code>s, removing all <code>Key</code>s with the <code>Value</code>s equal to one of the input <code>Value</code>s, and then produces updates via <code>onValueRemoved</code></li> </ul>"},{"location":"micro_utils/repos/index.html#keyvalues","title":"KeyValues","text":"<p>This type of repos contains muliple <code>Value</code>s by their unique <code>Key</code>. It is not guaranteed, that <code>Value</code>s list by any <code>Key</code> will contains only unique values, but in most cases <code>Value</code>s list will not contains copies/same objects.</p>"},{"location":"micro_utils/repos/index.html#readkeyvaluesrepo","title":"ReadKeyValuesRepo","text":"<p>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 <code>pagination</code>.</p>"},{"location":"micro_utils/repos/index.html#writekeyvaluesrepo","title":"WriteKeyValuesRepo","text":"<p>Contains write-only operations. This interface can be observed via its flows:</p> <ul> <li>onNewValue will pass <code>Key</code> and <code>Value</code> when <code>Value</code> has been added to the <code>Key</code></li> <li>onValueRemoved will pass <code>Key</code> and <code>Value</code> when <code>Value</code> has been removed for the <code>Key</code></li> <li>onDataCleared will pass <code>Key</code> when all its values has been removed by the <code>clear</code> operation</li> </ul> <p>Info</p> <p> In difference with other repos, not all the methods of write key values repo require collections.</p> <p>All the methods on <code>WriteKeyValuesRepo</code> have their variances with <code>pairs</code> (for set) or plain <code>vararg</code>s.</p> <ul> <li><code>add</code> will add <code>Value</code>s to their <code>Key</code>s without any removing of data</li> <li><code>clear</code> removes all <code>Value</code>s by <code>Key</code> and <code>Key</code> itself from repo</li> <li><code>clearWithValue</code> removes all <code>Value</code> with full clear of all data by <code>Key</code>s with incoming <code>Value</code></li> <li><code>remove</code> consumes <code>Map</code> of <code>Key</code>s and the <code>Value</code>s which should be removed for each <code>Key</code></li> <li><code>removeWithValue</code> will remove only <code>Value</code> from all <code>Key</code>s collections without their full wipe</li> <li><code>set</code> consumes <code>Map</code> of <code>Key</code>s and the <code>Value</code>s and will rewrite currently exists list of <code>Value</code>s and set the <code>Value</code>s for their <code>Key</code></li> </ul>"},{"location":"micro_utils/repos/inmemory.html","title":"In memory","text":"<p>In memory realizations contains several simple variants:</p> <ul> <li>MapCRUDRepo</li> <li>MapKeyValueRepo</li> <li>MapKeyValuesRepo</li> </ul> <p>Each realization contains <code>Write</code> and <code>Read</code> parents.</p> <p>There are several important moments:</p>"},{"location":"micro_utils/repos/inmemory.html#writemapcrudrepo-and-mapcrudrepo","title":"WriteMapCRUDRepo (and MapCRUDRepo)","text":"<p>It is an abstract repo with abstract functions: <code>updateObject</code> and <code>createObject</code>. Both functions require from realization to create <code>Registered</code> variant from incoming data and both will be called within repo locker.withWriteLock.</p> <p>You may use functions MapCRUDRepo with passing the callbacks <code>updateObject</code> and <code>createObject</code> which will be used in their realizations of default MapCRUDRepo variant</p>"},{"location":"navigation/index.html","title":"Navigation","text":"<p>This library uses koin as preferred DI in MVVM part</p> <p>Navigation is a library for simple management for your app views (or some other logics). In this library there are several important terms:</p> <ul> <li><code>Node</code> - is a core thing. Node itself contains current config and its state</li> <li><code>Chain</code> - some sequence of nodes. In one chain only the last one node can be active</li> </ul>"},{"location":"navigation/index.html#work-explanation","title":"Work explanation","text":"<ul> <li>Only the last (most deep) <code>node</code> can be <code>RESUMED</code></li> <li>All the <code>chain</code>s of resumed <code>node</code> will have status <code>RESUMED</code></li> <li>Only in the <code>chain</code> with status <code>RESUMED</code> there are <code>RESUMED</code> nodes</li> </ul> Statuses <p>There are 4 real statuses:</p> <ul> <li>New - Means that Node/Chain is just created (even before constructor) or has been fully destroyed (in context of navigation)</li> <li>Created - Means that Node/Chain is created or preparing for destroing</li> <li>Started - Means that Node/Chain is hidden and can be resumed/stopped at any time</li> <li>Resumed - Means that Node/Chain now active</li> </ul> <p>In fact node will retrieve 6 changes of statuses:</p> 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":"<p>Let\u2019s see the next sample:</p> 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 <p>we may say several things about the sample above:</p> <ul> <li>N2 is the latest node and it is <code>RESUMED</code></li> <li>N1 <code>PAUSED</code></li> <li>RootChain is <code>RESUMED</code></li> </ul> <p>So, we would like to add new node in the end of stack:</p> 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 <p>As we can see, N3 became <code>RESUMED</code> and N2 <code>PAUSED</code>. Let\u2019s try to remove N3:</p> 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":"<p>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:</p> 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 <p>Here has been created new N2Subchain with N3 node. Both them resumed because of:</p> <ul> <li>N2 is resumed. So, N2Subchain supposed to be resumed</li> <li>Due to N2Subhain is resumed and N3 is the latest node, it will be resumed too</li> </ul> <p>We may add new subchain to N1:</p> 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 <p>So, it has been added, but:</p> <ul> <li>Due to N1 paused state, N1Subchain have inherited it</li> <li>Due to N1Subhain is paused, all its nodes paused too</li> </ul> <p>And now we may remove N2 node. This action will trigger next changes:</p> 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 <p>What has happened:</p> <ol> <li>We solved to remove N2 node. Status is changing to stopped</li> <li>N2Subchain must be stopped</li> <li>N3 must be stopped as well</li> </ol> <p>Stopping in context of navigation means destroying</p>"},{"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":"<p>Traditionally, you need to add dependency to your project. Currently, there are two types of artifacts:</p> <ul> <li><code>Core</code> - only necessary tools for your projects</li> <li><code>MVVM</code> - Model-View-ViewModel architecture tools + <code>Core</code> components</li> </ul> Artifact Purpose Dependency <code>Core</code> Only necessary tools for your projects <code>implementation \"dev.inmo:navigation.core:$navigation_version\"</code> <code>MVVM</code> Model-View-ViewModel architecture tools + <code>Core</code> components <code>implementation \"dev.inmo:navigation.mvvm:$navigation_version\"</code>"},{"location":"navigation/getting-started.html#get-started","title":"Get started","text":"<p>After you have added your dependency, you should initialize navigation. There are several important things:</p> <ol> <li><code>Config</code> - it is an instance of any class which extending the <code>NavigationNodeDefaultConfig</code> in common case</li> <li><code>Factory</code> - usually object which may create a node or some required part for node</li> </ol> <p>For example: lets imagine that we have a node <code>Main</code>. Here what should we do to create a node and make it workable in navigation:</p> <pre><code>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</code></pre> <p>Both <code>JS</code> and <code>Android</code> platforms require <code>ViewModel</code> for their <code>MVVM</code> node variants, but it can be common as well as <code>MainConfig</code>:</p> <pre><code>class MainViewModel(\n node: NavigationNode<MainConfig, NavigationNodeDefaultConfig>\n) : ViewModel(\n node\n)\n</code></pre>"},{"location":"navigation/getting-started.html#js-part","title":"JS part","text":"<pre><code>// 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</code></pre> <p>Data below is under TBD</p>"},{"location":"navigation/getting-started.html#android","title":"Android","text":"<p>In Android there is one important note: you will not directly work with nodes. In fact it will be required to create special <code>NodeFragment</code>:</p> <pre><code>// 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</code></pre> <p>Initialization is different on the platforms, so, lets take a look at each one.</p>"},{"location":"navigation/getting-started.html#js","title":"JS","text":"<p>In <code>JavaScript</code> it looks like:</p> <pre><code>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</code></pre> <ol> <li>Creating of default root chain config holder. It must be root chain because of the chain work with statuses changes</li> <li>Creating of default root node config holder. This type contains config of the first node, its subnode and subchains lists</li> <li>Default root config</li> <li>Subnode of root node. In this case it is <code>null</code>, but can be any <code>ConfigHolder.Node</code></li> <li>Subchains of default root node</li> <li>Configurations changes repo saver. By default it is <code>cookies</code> (<code>localStorage</code>) store</li> <li>Register config for serialization to let configs repo serializer to know how to serialize <code>MainConfig</code></li> <li>Flag that the chains without any node will be dropped automatically</li> <li>In fact here can be factory aggregator, for example: <pre><code>val factories: List<NavigationNodeFactory<NavigationNodeDefaultConfig>>\nNavigationNodeFactory<NavigationNodeDefaultConfig> { chainHolder, config ->\n factories.firstNotNullOfOrNull { it.createNode(chainHolder, config) }\n}\n</code></pre></li> </ol>"},{"location":"plagubot/index.html","title":"PlaguBot","text":"<p>PlaguBot is a small framework for unifying developing of modules of bots. It is built with two parts:</p> <ul> <li>Plugin</li> <li>Bot</li> </ul>"},{"location":"plagubot/index.html#plugin","title":"Plugin","text":"<p>Plugin is a partially independent part of bot. Plugin have several parts:</p> <ul> <li><code>setupBotClient</code> - method to configure telegram bot in case you need it. Called synchronously when <code>TelegramBot</code> initializing in <code>single</code> in <code>setupDI</code> of <code>PlaguBot</code></li> <li><code>setupBotPlugin</code> - method to start/configure your bot actions. Called asynchronously in <code>buildBehaviourWithFSM</code> in <code>startPlugin</code> of <code>PlaguBot</code></li> </ul> <p>Plugin realization should be an <code>object</code> or <code>class</code> with empty constructor.</p>"},{"location":"plagubot/index.html#bot","title":"Bot","text":"<p>Most important of bot is <code>main</code> function (full reference: <code>dev.inmo.plagubot.AppKt</code>). It consumes one argument - path to config.</p> <p>Bot is initializing with the next algorithm:</p> <p>OLD</p> 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":"<p>There are several important opportunities out of the box:</p> <ul> <li>Database access</li> <li>Config access</li> <li>Bot setup</li> <li>Json format</li> <li>Bot itself</li> </ul>"},{"location":"plagubot/opportunities_out_of_the_box.html#database-access","title":"Database access","text":"<p>You may access database in your plugin via koin in <code>setupBotPlugin</code> or as parameter in <code>setupDI</code>:</p> <pre><code>object YourPlugin : Plugin {\n // ...\n override fun Module.setupDI(\n database: Database, // database\n params: JsonObject\n ) {\n // ...\n }\n}\n</code></pre> <p>It is simple Exposed database and you may use it in your tables.</p>"},{"location":"plagubot/opportunities_out_of_the_box.html#config-access","title":"Config access","text":"<p>As you may see, in the <code>setupDI</code> function we also have <code>params</code> parameter with source configuration json. In case you wish to declare and work with your own config in plugin, you may use next snippet:</p> <pre><code>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</code></pre> <ol> <li>In this case your config will looks like: <pre><code>{\n \"params1\": \"SomeString\",\n \"params2\": 42\n}\n</code></pre></li> <li>In this case your config will looks like: <pre><code>{\n \"yourplugin\": {\n \"params1\": \"SomeString\",\n \"params2\": 42\n }\n}\n</code></pre></li> </ol>"},{"location":"plagubot/opportunities_out_of_the_box.html#bot-setup","title":"Bot setup","text":"<p>Out of the box you may setup several things in bot:</p> <ul> <li><code>StatesManager<State></code> (1)</li> <li><code>DefaultStatesManagerRepo<State></code> (2)</li> <li>Any amount of <code>OnStartContextsConflictResolver</code> (3)</li> <li>Any amount of <code>OnUpdateContextsConflictResolver</code> (4)</li> <li><code>StateHandlingErrorHandler<State></code> (5)</li> </ul> <ol> <li>For this use next code in <code>setupDI</code>: <pre><code>// Your plugin\n override fun Module.setupDI(database: Database, params: JsonObject) {\n single<StatesManager<State>> {\n // Your StatesManager<State> initialization\n }\n }\n</code></pre></li> <li>For this use next code in <code>setupDI</code>: <pre><code>// Your plugin\n override fun Module.setupDI(database: Database, params: JsonObject) {\n single<DefaultStatesManagerRepo<State>> {\n // Your DefaultStatesManagerRepo<State> initialization\n }\n }\n</code></pre></li> <li>You may declare any amount of <code>OnStartContextsConflictResolver</code>. <code>PlaguBot</code> will take first non-null result of resolvers from DI and use in default states manager. To declare, use next snippet: <pre><code>// 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</code></pre></li> <li>You may declare any amount of <code>OnUpdateContextsConflictResolver</code>. <code>PlaguBot</code> will take first non-null result of resolvers from DI and use in default states manager. To declare, use next snippet: <pre><code>// 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</code></pre></li> <li>You may declare only one <code>StateHandlingErrorHandler<State></code>. This handler will be called each time when some state will be handled with exception and may return <code>null</code> or new state instead old one: <pre><code>// 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</code></pre></li> </ol>"},{"location":"services/index.html","title":"Services information","text":"<p>There are several public services I am hosting or have created:</p> <ol> <li>I am using this tool in all my libraries :)</li> </ol>"},{"location":"services/index.html#tools","title":"Tools","text":"<ul> <li>Kotlin Publication Groovy Scripts builder - Builder of commonized scripts on groovy for publication of libraries (1)</li> <li>Krontab Predictor - Special <code>KrontabSctring</code> builder for Krontab</li> </ul>"},{"location":"services/index.html#services","title":"Services","text":"<ul> <li>Git - Here I am making some backups of my repos and hosting some semi-private projects</li> <li>Nexus - Nexus for libraries artifacts. It is in plans to duplicate all libraries there</li> </ul>"},{"location":"services/index.html#kdocs","title":"KDocs","text":"<ul> <li>KTgBotAPI - for KTgBotAPI :)</li> <li>KSLog - for KSLog :)</li> <li>MicroUtils - for MicroUtils :)</li> <li>Navigation - for Navigation :)</li> </ul>"},{"location":"tgbotapi/index.html","title":"TelegramBotAPI","text":"<p>Hello! This is a set of libraries for working with Telegram Bot API.</p>"},{"location":"tgbotapi/index.html#examples","title":"Examples","text":"<p>There are several things you need to do to launch examples below:</p> <ul> <li>Add <code>mavenCentral()</code> to your project repositories<ul> <li>Maven variant</li> </ul> </li> <li>Add dependency <code>implementation \"dev.inmo:tgbotapi:$tgbotapi_version\"</code><ul> <li>Replace <code>tgbotapi_version</code> with exact version (see last one in the table above) or put variable with this name in project</li> <li>Alternative variant for maven here</li> </ul> </li> </ul> <p>More including instructions available here. Other configuration examples:</p> <ul> <li>For multiplatform</li> <li>For JVM</li> </ul>"},{"location":"tgbotapi/index.html#most-common-example","title":"Most common example","text":"<pre><code>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</code></pre> <p>In this example you will see information about this bot at the moment of starting and answer with <code>Hi:)</code> every time it gets message <code>/start</code></p>"},{"location":"tgbotapi/index.html#handling-only-last-messages","title":"Handling only last messages","text":"<pre><code>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</code></pre> <p>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)</p>"},{"location":"tgbotapi/index.html#build-a-little-bit-more-complex-behaviour","title":"Build a little bit more complex behaviour","text":"<pre><code>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</code></pre>"},{"location":"tgbotapi/index.html#more-examples","title":"More examples","text":"<p>You may find examples in this project. Besides, you are always welcome in our chat.</p>"},{"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 <code>Failed to load class \"org.slf4j.impl.StaticLoggerBinder\"</code>?","text":"<pre><code>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</code></pre> <p>This error is just a warning about the absence of slf4j setup. You may fix this error by following to stackoverflow answer</p>"},{"location":"tgbotapi/faq.html#how-to-filter-updates-in-some-part-of-behaviourbuilder","title":"How to filter updates in some part of <code>BehaviourBuilder</code>?","text":"<p>You may create subcontext with <code>BehaviourBuilder.</code><code>createSubContextAndDoWithUpdatesFilter</code> and pass there <code>updatesUpstreamFlow</code> parameter with any operations over parent behaviour builder:</p> <pre><code>buildBehaviourWithLongPolling {\n createSubContextAndDoWithUpdatesFilter(\n updatesUpstreamFlow = filter { /* some condition */ },\n stopOnCompletion = false // disable stopping of sub context after setup\n ) {\n onCommand() //...\n }\n}\n</code></pre>"},{"location":"tgbotapi/faq.html#additional-info","title":"Additional info","text":"<ul> <li>Flows docs</li> <li>BehaviourBuilder</li> </ul>"},{"location":"tgbotapi/faq.html#cases","title":"Cases","text":"<ul> <li>Filtering of chats and users: <pre><code> updatesUpstreamFlow = filter { it.sourceChat() ?.id == requiredChatId || it.sourceUser() ?.id == requiredUserId }\n</code></pre><ul> <li>See:<ul> <li>Update.sourceChat</li> <li>Update.sourceUser</li> </ul> </li> </ul> </li> </ul>"},{"location":"tgbotapi/logs.html","title":"Logging","text":"<p>In this library we are using KSLog for logging of events in telegram bots. There are several ways to set it up and configure.</p> <pre><code>// (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</code></pre> <ol> <li>This variant will set GLOBAL DEFAULT logger. For example, if you will use somewhere <code>TagLogger</code>, it will use <code>KSLog.default</code> under the hood</li> <li>All the bots created after this setup will use new logger until more specified logger configured (see below)</li> <li>Passing of <code>logger</code> variable to the <code>KtorRequestsExecutor</code> or one of factories <code>telegrabBot</code> will lead to granular setup of logging</li> </ol>"},{"location":"tgbotapi/dsls/keyboards.html","title":"Keyboards","text":"<p>In the telegram system there are two types of keyboards:</p> Reply Inline Keyboard for each user in the chat Keyboard linked to the certain message <p>Low-level way to create keyboard looks like in the next snippet:</p> <pre><code>ReplyKeyboardMarkup(\n matrix {\n row {\n add(SimpleKeyboardButton(\"Simple text\"))\n // ...\n }\n // ...\n }\n)\n</code></pre> <p>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:</p> <pre><code>// 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</code></pre>"},{"location":"tgbotapi/dsls/live-location.html","title":"Live Location","text":"<p>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:</p> <ul> <li>Directly via API calls (sendLiveLocation and editLiveLocation)</li> <li>startLiveLocation</li> <li>handleLiveLocation</li> </ul>"},{"location":"tgbotapi/dsls/live-location.html#sendlivelocation","title":"sendLiveLocation","text":"<p>In the Bot API there is no independent <code>sendLiveLocation</code> method, instead it is suggested to use sendLocation with setting up <code>live_period</code>. 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.</p> <p>Anyway, in common case the logic looks like:</p> <ul> <li>Send sendLiveLocation</li> <li>Use editLiveLocation to change it during its lifetime</li> <li>Use stopLiveLocation to abort it before lifetime end</li> </ul>"},{"location":"tgbotapi/dsls/live-location.html#startlivelocation","title":"startLiveLocation","text":"<p>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:</p> <ul> <li>startLiveLocation</li> <li>Use LiveLocationProvider#updateLocation to update location and optionally add inline keyboard</li> <li>Use LiveLocationProvider#close to abort live location before its end</li> </ul> <p>Besides, <code>LiveLocationProvider</code> contains different useful parameters about live location</p>"},{"location":"tgbotapi/dsls/live-location.html#handlelivelocation","title":"handleLiveLocation","text":"<p>This way of live locations handling is based on coroutines Flow and allow you to pass some external <code>Flow</code> with EditLiveLocationInfo. So, workflow:</p> <ul> <li>Create your own flow of locations. For example: <pre><code>flow {\n var i = 0\n while (isActive) {\n val newInfo = EditLiveLocationInfo(\n latitude = i.toDouble(),\n longitude = i.toDouble(),\n replyMarkup = flatInlineKeyboard {\n dataButton(\"Cancel\", \"cancel\")\n }\n )\n emit(newInfo)\n i++\n delay(10000L) // 10 seconds\n }\n}\n</code></pre></li> <li>In case you needed, create your collector to store the message with live location: <pre><code>val currentMessageState = MutableStateFlow<ContentMessage<LocationContent>?>(null)\n</code></pre></li> <li>Start handle live location. handleLiveLocation works synchronosly (in current coroutine) and will ends only when your flow will ends. Thats why there are two ways to call it: <pre><code>handleLiveLocation(\n it.chat.id,\n locationsFlow,\n sentMessageFlow = FlowCollector { currentMessageState.emit(it) }\n)\n// this code will be called after `locationsFlow` will ends\n</code></pre> OR <pre><code>scope.launch {\n handleLiveLocation(\n it.chat.id,\n locationsFlow,\n sentMessageFlow = FlowCollector { currentMessageState.emit(it) }\n )\n}\n// this code will be called right after launch will be completed\n</code></pre></li> </ul> <p>See our example to get more detailed sample</p>"},{"location":"tgbotapi/dsls/text.html","title":"Text","text":"<p>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:</p> <pre><code>val sources = \"Regular start of text \" + bold(\"with bold part\") + italic(\"and italic ending\")\n</code></pre> <p>But there is a little bit more useful way: entities builder:</p> <pre><code>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</code></pre> <p>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 <code>TextSource</code>s. 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.</p>"},{"location":"tgbotapi/guides/keyboards.html","title":"Keyboards Guide","text":"<p>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.</p>"},{"location":"tgbotapi/guides/keyboards.html#introduction","title":"Introduction","text":""},{"location":"tgbotapi/guides/keyboards.html#keyboard-types","title":"Keyboard Types","text":"<p>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.</p> <p></p> <p>Resize option</p> <p> In the screenshots above (and in the most others) you may see usage of reply keyboards without <code>resize_keyboard</code>. In case you will use <code>resize_keyboard = true</code> the keyboard will be smaller.</p> <p>Note the differences in the way these keyboards are shown to a user.</p> <p>A reply keyboard is shown under the message input field. It replaces the device\u2019s native input method on a mobile device.</p> <p>An inline keyboard is shown as a part of the message in the chat.</p>"},{"location":"tgbotapi/guides/keyboards.html#simple-keyboard-interactions","title":"Simple Keyboard Interactions","text":"<p>When a user clicks on a simple reply keyboard button, its text is just sent in the chat.</p> <p>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.</p> <p></p> <p>It\u2019s a common mistake to forget to handle callback queries</p> <p> 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!</p> <p>As new messages arrive, a reply keyboard will stay there, while the inline keyboard will stick to the message and move with it.</p> <p></p> <p>Ups\u2026 The reply keyboard is now far away from the message it was sent with.</p> <p>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.</p> <p>It\u2019s a common mistake to forget to remove or replace reply keyboards</p> <p> It leads to the keyboards being shown forever. Don\u2019t forget to remove reply keyboards when you don\u2019t need them anymore!</p> <p>You also may use option <code>one_time_keyboard</code> and the keyboard will be automatically removed after user interaction</p> <p>An inline keyboard could also be removed or changed by editing the original message it was attached to.</p>"},{"location":"tgbotapi/guides/keyboards.html#extended-keyboard-interactions","title":"Extended Keyboard Interactions","text":"<p>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.</p> <p>For the full list of options, see the official documentation on reply and inline keyboards.</p> <p></p>"},{"location":"tgbotapi/guides/keyboards.html#basic-api-classes","title":"Basic API & Classes","text":"<p>Now, that you know the basics, let\u2019s see how to use the library.</p>"},{"location":"tgbotapi/guides/keyboards.html#keyboards","title":"Keyboards","text":"<p>In Telegram Bot API keyboards are sent to the user as a part of an interaction via the <code>reply_markup</code> parameter. More specifically, this parameter is available:</p> <ul> <li>in the <code>sendXXX</code> methods, like <code>sendMessage</code>, <code>sendPhoto</code>, <code>sendSticker</code>, etc.</li> <li>in the <code>copyMessage</code> method</li> <li>in the <code>editMessageXXX</code> methods, like <code>editMessageText</code>, <code>editMessageCaption</code>, <code>editMessageReplyMarkup</code>, etc. This also includes <code>stopXXX</code> methods like the <code>stopMessageLiveLocation</code> method.</li> </ul> <p>Tip</p> <p><code>editMessageReplyMarkup</code> is specifically designed to edit a message\u2019s inline keyboard.</p> <p>Sending inline keyboards is also supported in inline mode through the <code>reply_markup</code> parameter of the <code>InlineQueryResult</code> type and its inheritors. However, this inline mode is unrelated to the inline keyboards.</p> <p>The <code>reply_markup</code> parameter accepts four different types. Two of them \u2014 <code>ReplyKeyboardMarkup</code> and <code>InlineKeyboardMarkup</code> \u2014 correspond to the reply and inline keyboards respectively. The <code>ReplyKeyboardRemove</code> type is used to remove reply keyboards, but it\u2019s not a keyboard itself. The last one, <code>ForceReply</code>, 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.</p> <p></p> <p>Now, in the library, the <code>WithReplyMarkup</code> is a marker interface for all the interactions which could have a <code>replyMarkup</code> (represents <code>reply_markup</code>) parameter. It is extended by the <code>ReplyingMarkupSendMessageRequest</code>, and then, finally, by classes like <code>SendTextMessage</code>. This, basically, corresponds to the Telegram Bot API.</p> <p>Note</p> <p>You may see all the inheritors of <code>WithReplyMarkup</code> interfaces in the corresponding KDoc</p> <p>The other way to send a keyboard is through the <code>replyMarkup</code> parameter of the numerous extension methods, like <code>sendMessage</code>. Those are just convenient wrappers around general interaction classes, like the aforementioned <code>SendTextMessage</code>.</p>"},{"location":"tgbotapi/guides/keyboards.html#buttons","title":"Buttons","text":"<p>As we already know, keyboards consist of buttons. Button classes reside in the <code>dev.inmo.tgbotapi.types.buttons</code> package.</p> <p>The base class for the reply keyboard buttons is the <code>KeyboardButton</code>. The base class for the inline keyboard buttons is the <code>InlineKeyboardButton</code>.</p> <p>See their inheritors for the full list of the available buttons. The names are pretty self-explanatory and correspond to the Telegram Bot API.</p> <p>For example, to send a simple reply keyboard button, use the <code>SimpleKeyboardButton</code> class. To request a contact from the user through the reply, use the <code>RequestContactKeyboardButton</code> class. To attach a URL button to the message, use the <code>URLInlineKeyboardButton</code>. And to attach a callback button, use the <code>CallbackDataInlineKeyboardButton</code>.</p> <p>You get the idea.</p> <p>So, to send a reply keyboard use the following code:</p> <pre><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</code></pre> <p>And here is how you send a basic inline keyboard:</p> <pre><code>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</code></pre> <p></p> <p>When we\u2019re done with this simple quiz, we can remove the keyboard with the following code:</p> <pre><code>bot.sendMessage(\n chatId = chat,\n text = \"You're goddamn right!\",\n replyMarkup = ReplyKeyboardRemove()\n)\n</code></pre> <p>Note</p> <p>Don\u2019t forget to remove the reply keyboards!</p>"},{"location":"tgbotapi/guides/keyboards.html#matrices","title":"Matrices","text":"<p>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:</p> <pre><code>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</code></pre> <p></p> <p>This way of building matrices is not very convenient, so the library provides a few eloquent DSLs to simplify that.</p> <p>First, there are <code>matrix</code> and <code>row</code>, so the keyboard above can be built like this:</p> <p><pre><code>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</code></pre> </p> <p>Note</p> <p>Those plus signs are mandatory.</p> <p>Note</p> <p>There are two different <code>row</code> functions here. Can you spot the difference?</p> <p>A single-row matrix can be built with a <code>flatMatrix</code>:</p> <pre><code>flatMatrix {\n +CallbackDataInlineKeyboardButton(\"1\", \"1\")\n +CallbackDataInlineKeyboardButton(\"2\", \"2\")\n +CallbackDataInlineKeyboardButton(\"3\", \"3\")\n +CallbackDataInlineKeyboardButton(\"4\", \"4\")\n +CallbackDataInlineKeyboardButton(\"5\", \"5\")\n}\n</code></pre> <p>But the most convenient way to build a simple keyboard is to use the constructor-like methods: <code>InlineKeyboardMarkup</code> and <code>ReplyKeyboardMarkup</code>. Note, that they are named just like the corresponding constructor, but take a vararg of buttons. They create flat matrices, i.e. single rows.</p>"},{"location":"tgbotapi/guides/keyboards.html#keyboards-dsl","title":"Keyboards DSL","text":"<p>Finally, there are <code>inlineKeyboard</code> and <code>replyKeyboard</code></p> <p>DSL methods above rely on Kotlin\u2019s feature of receivers and extensions. So, the magic is done by <code>MatrixBuilder</code> and <code>RowBuilder</code>. 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.</p> <p>Another bonus of using these DSLs is button builders, like <code>payButton</code>, <code>dataButton</code>, and <code>urlButton</code>:</p> <pre><code>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</code></pre> <p>Reply keyboard builders provide similar extensions, e.g. <code>requestLocationButton</code>.</p> <p>So, choose the style you like \u2014 from plain Kotlin lists to sweet DSLs \u2014 and use it!</p>"},{"location":"tgbotapi/guides/keyboards.html#working-with-keyboards","title":"Working with keyboards","text":"<p>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.</p> <p>On the other hand, the library is heavily typed, so the actual type of update you would receive varies.</p>"},{"location":"tgbotapi/guides/keyboards.html#reply-keyboards","title":"Reply keyboards","text":"<p>As it was said, reply keyboards cause Telegram clients to send regular messages back to the bot. Peruse this example:</p> <pre><code>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</code></pre> <p>Note</p> <p>Read more about <code>buildBehaviourWithLongPolling</code> here</p> <p>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.</p> <p>And here is how it works (the user selects the options in the order):</p> <p>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.</p> <p>And don\u2019t be a rat in real life: remove the keyboards with the <code>ReplyKeyboardRemove</code> after you\u2019ve received the input! Otherwise, a keyboard will stay there indefinitely.</p>"},{"location":"tgbotapi/guides/keyboards.html#inline-keyboards","title":"Inline keyboards","text":"<p>Finally, to master the keyboards, you need to know how to handle the inline ones.</p> <p>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.</p> <p>The quiz could be implemented this way:</p> <pre><code>// 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</code></pre> <p>A few important things to note here.</p> <p>First, the data buttons (they have the <code>CallbackDataInlineKeyboardButton</code> type, but in the code we used a neat DSL) must have unique <code>data</code>. If the <code>data</code> 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).</p> <p>Second, the way you handle inline keyboards is different from the way you handle reply keyboards. Bot API will send updates with a <code>callback_query</code> field populated. This field, of a <code>CallbackQuery</code> type, represents incoming callbacks from callback buttons in inline keyboards. The library turns them into multiple callback types, like the <code>DataCallbackQuery</code> we used in the example. Finally, to handle these callbacks you could use <code>onDataCallbackQuery</code>. Alternatively, if you\u2019re not using any DSLs, you have to handle the <code>CallbackQueryUpdate</code> update type.</p> <p>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 <code>answerCallbackQuery</code> function. Otherwise, the button will remain highlighted. Telegram clients will eventually remove the highlight, but it\u2019s still frustrating.</p> <p>Finally, you could choose between two styles of acknowledgment: a simple toast-like message or a modal alert. The <code>showAlert</code> flag controls this behavior.</p> <p>And here is the demo of the quiz:</p>"},{"location":"tgbotapi/guides/keyboards.html#conclusion","title":"Conclusion","text":"<p>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.</p>"},{"location":"tgbotapi/introduction/before-any-bot-project.html","title":"Before any bot project","text":"<p>There are several places you need to visit for starting work with any Telegram Bot framework on any language:</p> <ul> <li>Bots info introduction</li> <li>Telegram Bot API reference (you can skip it, but it could be useful to know some specific cases in Telegram Bot API)</li> </ul> <p>Anyway, the most important link is How do I create a bot? inside of Telegram Bot API</p>"},{"location":"tgbotapi/introduction/before-any-bot-project.html#next-steps","title":"Next steps","text":"<ul> <li>Including in your project</li> </ul>"},{"location":"tgbotapi/introduction/first-bot.html","title":"First bot","text":"<p>Examples info</p> <p> A lot of examples with using of Telegram Bot API you can find in this github repository</p>"},{"location":"tgbotapi/introduction/first-bot.html#the-most-simple-bot","title":"The most simple bot","text":"<p>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:</p> <pre><code>suspend fun main(vararg args: String) {\n val botToken = args.first()\n val bot = telegramBot(botToken)\n println(bot.getMe())\n}\n</code></pre> <p>So, let\u2019s get understanding, about what is going on:</p> <ol> <li><code>suspend fun main(vararg args: String)</code>:<ul> <li><code>suspend</code> required for making of requests inside of this function. For more info you can open official documentation for coroutins. In fact, <code>suspend fun main</code> is the same that <code>fun main() = runBlocking {}</code> from examples</li> </ul> </li> <li><code>val botToken = args.first()</code>: here we are just getting the bot token from first arguments of command line</li> <li><code>val bot = telegramBot(botToken)</code> : inside of <code>bot</code> will be RequestsExecutor object which will be used for all requests in any project with this library</li> <li><code>println(bot.getMe())</code>: here happens calling of getMe extension</li> </ol> <p>As a result, we will see in the command line something like</p> <pre><code>ExtendedBot(id=ChatId(chatId=123456789), username=Username(username=@first_test_ee17e8_bot), firstName=Your bot name, lastName=, canJoinGroups=false, canReadAllGroupMessages=false, supportsInlineQueries=false)\n</code></pre>"},{"location":"tgbotapi/introduction/including-in-your-project.html","title":"Including in your project","text":"<p>There are three projects:</p> <ul> <li><code>TelegramBotAPI Core</code> - project with base for all working with Telegram Bot API</li> <li><code>TelegramBotAPI API Extensions</code> - extension of <code>TelegramBotAPI</code> with functions for more comfortable work with Telegram Bot API</li> <li><code>TelegramBotAPI Utils Extensions</code> - extension of <code>TelegramBotAPI</code> with functions for extending of different things like retrieving of updates</li> </ul> <p>TelegramBotAPI</p> <p>Also, there is an aggregator-version <code>tgbotapi</code>, which will automatically include all projects above. It is most recommended version due to the fact that it is including all necessary tools around <code>TelegramBotAPI Core</code>, but it is optionally due to the possible restrictions on the result methods count (for android) or bundle size</p> <p>Examples</p> <p>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</p>"},{"location":"tgbotapi/introduction/including-in-your-project.html#notice-about-repository","title":"Notice about repository","text":"<p>To use this library, you will need to include <code>Maven Central</code> repository in your project</p>"},{"location":"tgbotapi/introduction/including-in-your-project.html#buildgradle","title":"build.gradle","text":"<pre><code>mavenCentral()\n</code></pre>"},{"location":"tgbotapi/introduction/including-in-your-project.html#pomxml","title":"pom.xml","text":"<pre><code><repository>\n <id>central</id>\n <name>mavenCentral</name>\n <url>https://repo1.maven.org/maven2</url>\n</repository>\n</code></pre>"},{"location":"tgbotapi/introduction/including-in-your-project.html#dev-channel","title":"Dev channel","text":"<p>Besides, there is developer versions repo. To use it in your project, add the repo in <code>repositories</code> section:</p> Gradle <pre><code>maven {\n url \"https://git.inmo.dev/api/packages/InsanusMokrassar/maven\"\n}\n</code></pre> Maven <pre><code><repository>\n <id>dev.inmo</id>\n <name>InmoDev</name>\n <url>https://git.inmo.dev/api/packages/InsanusMokrassar/maven</url>\n</repository>\n</code></pre>"},{"location":"tgbotapi/introduction/including-in-your-project.html#telegrambotapi","title":"TelegramBotAPI","text":"<p>As <code>tgbotapi_version</code> variable in next snippets will be used variable with next last published version:</p> <p></p>"},{"location":"tgbotapi/introduction/including-in-your-project.html#buildgradle_1","title":"build.gradle","text":"<pre><code>implementation \"dev.inmo:tgbotapi:$tgbotapi_version\"\n</code></pre>"},{"location":"tgbotapi/introduction/including-in-your-project.html#pomxml_1","title":"pom.xml","text":"<pre><code><dependency>\n <groupId>dev.inmo</groupId>\n <artifactId>tgbotapi</artifactId>\n <version>${tgbotapi_version}</version>\n</dependency>\n</code></pre>"},{"location":"tgbotapi/introduction/including-in-your-project.html#telegrambotapi-core","title":"TelegramBotAPI Core","text":"<p>As <code>tgbotapi_version</code> variable in next snippets will be used variable with next last published version:</p> <p></p>"},{"location":"tgbotapi/introduction/including-in-your-project.html#buildgradle_2","title":"build.gradle","text":"<pre><code>implementation \"dev.inmo:tgbotapi.core:$tgbotapi_version\"\n</code></pre>"},{"location":"tgbotapi/introduction/including-in-your-project.html#pomxml_2","title":"pom.xml","text":"<pre><code><dependency>\n <groupId>dev.inmo</groupId>\n <artifactId>tgbotapi.core</artifactId>\n <version>${tgbotapi_version}</version>\n</dependency>\n</code></pre>"},{"location":"tgbotapi/introduction/including-in-your-project.html#telegrambotapi-api-extensions","title":"TelegramBotAPI API Extensions","text":"<p>As <code>tgbotapi_version</code> variable in next snippets will be used variable with next last published version:</p> <p></p>"},{"location":"tgbotapi/introduction/including-in-your-project.html#buildgradle_3","title":"build.gradle","text":"<pre><code>implementation \"dev.inmo:tgbotapi.api:$tgbotapi_version\"\n</code></pre>"},{"location":"tgbotapi/introduction/including-in-your-project.html#pomxml_3","title":"pom.xml","text":"<pre><code><dependency>\n <groupId>dev.inmo</groupId>\n <artifactId>tgbotapi.api</artifactId>\n <version>${tgbotapi_version}</version>\n</dependency>\n</code></pre>"},{"location":"tgbotapi/introduction/including-in-your-project.html#telegrambotapi-utils-extensions","title":"TelegramBotAPI Utils Extensions","text":"<p>As <code>tgbotapi_version</code> variable in next snippets will be used variable with next last published version:</p> <p></p>"},{"location":"tgbotapi/introduction/including-in-your-project.html#buildgradle_4","title":"build.gradle","text":"<pre><code>implementation \"dev.inmo:tgbotapi.utils:$tgbotapi_version\"\n</code></pre>"},{"location":"tgbotapi/introduction/including-in-your-project.html#pomxml_4","title":"pom.xml","text":"<pre><code><dependency>\n <groupId>dev.inmo</groupId>\n <artifactId>tgbotapi.utils</artifactId>\n <version>${tgbotapi_version}</version>\n</dependency>\n</code></pre>"},{"location":"tgbotapi/introduction/including-in-your-project.html#next-steps","title":"Next steps","text":"<ul> <li>Proxy setup</li> <li>First bot</li> </ul>"},{"location":"tgbotapi/introduction/proxy-setup.html","title":"Proxy setup","text":"<p>In some locations Telegram Bots API urls will be unavailable. In this case all examples will just throw exception like:</p> <pre><code>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</code></pre> <p>There are several ways to solve this problem:</p> <ul> <li>Built-in proxy config (will require some socks or http proxy server)</li> <li>System-configured VPN or proxy</li> <li>Your own Bot API Server</li> </ul>"},{"location":"tgbotapi/introduction/proxy-setup.html#using-ktor-client-built-in-proxy","title":"Using Ktor Client built-in proxy","text":"<p>First of all, you will need to use one more library:</p> <p>build.gradle:</p> <pre><code>implementation \"io.ktor:ktor-client-okhttp:2.3.5\"\n</code></pre> <p>Dependency note</p> <p> In the snippet above was used version <code>2.3.5</code> which is actual for <code>TelegramBotAPI</code> at the moment of filling this documentation (<code>october 11 2023</code>, <code>TelegramBotAPI</code> version <code>9.2.2</code>) and you can update version of this dependency in case if it is outdated.</p> <p>For configuring proxy for your bot inside your program, you can use next snippet:</p> <pre><code>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</code></pre> <ol> <li>Here we are just creating variable <code>botToken</code></li> <li>Start creating bot</li> <li>Setting <code>HttpClient</code> of our bot. On the time of documentation filling, <code>OkHttp</code> is one of the engines in <code>Ktor</code> system which supports socks proxy. More you can read on Ktor site in subparts about engines and proxy</li> <li>Start setting up of <code>HttpClient</code> engine</li> <li>Start setting up of <code>HttpClient</code> engine configuration</li> <li>Start setting up of proxy</li> <li>Creating proxy info object</li> <li>Saying that it is <code>Socks</code> proxy</li> <li>Creating address. Note that <code>\"127.0.0.1\"</code> and <code>1080</code> are configurable parameters</li> </ol>"},{"location":"tgbotapi/introduction/proxy-setup.html#more-complex-and-flexible-variant","title":"More complex and flexible variant","text":"<p>You may try to use custom engine for ktor. For example:</p> <pre><code>// 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</code></pre> <ol> <li>Start creating telegram bot</li> <li>Proxy host</li> <li>Proxy port</li> <li>Username for authentication. It is optional in case your proxy do not need auth</li> <li>Password for authentication. It is optional in case your proxy do not need auth</li> <li>Creating of proxy address for <code>Proxy</code></li> <li>Proxy address and type information</li> <li>Proxy authentication info. It is optional in case your proxy do not need auth</li> <li>Setting up of authenticator. It is optional in case your proxy do not need auth</li> <li>Overriding of method that will return authentication info</li> <li>In case when request has been sent to the proxy (common request) - using authentication</li> <li>Creating of HttpClient and start configure it</li> <li>Start setup engine</li> <li>Start setup engine config</li> <li>Setting up of proxy information</li> </ol>"},{"location":"tgbotapi/introduction/proxy-setup.html#next-steps","title":"Next steps","text":"<ul> <li>First bot</li> </ul>"},{"location":"tgbotapi/logic/api-extensions.html","title":"API Extensions","text":"<p>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 <code>bot.getUpdates()</code> instead of <code>bot.execute(GetUpdates())</code>, but there are several other things you will achieve with that syntax.</p>"},{"location":"tgbotapi/logic/api-extensions.html#bot-builder","title":"Bot builder","text":"<p>This functionality allow you to build bot in more unified and comfortable way than standard creating with <code>telegramBot</code> function</p> <pre><code>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</code></pre>"},{"location":"tgbotapi/logic/api-extensions.html#downloading-of-files","title":"Downloading of files","text":"<p>In standard library requests there are no way to download some file retrieved in updates or after requests. You may use syntax like <code>bot.downloadFile(file)</code> where <code>file</code> is <code>TelegramMediaFile</code> from telegram, <code>FileId</code> or even <code>PathedFile</code> from GetFile request (sources).</p>"},{"location":"tgbotapi/logic/api-extensions.html#live-location","title":"Live location","text":"<p>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 <code>updateLocation</code> for retrieved LiveLocationProvider.</p>"},{"location":"tgbotapi/logic/api-extensions.html#what-is-next","title":"What is next?","text":"<p>There are several things you may read next:</p> <ul> <li>Updates retrieving</li> <li>Read about second level of working with library</li> <li>Read about BehaviourBuilder</li> </ul>"},{"location":"tgbotapi/logic/behaviour-builder-with-fsm.html","title":"Behaviour Builder with FSM","text":"<p>Behaviour builder with FSM is based on the MicroUtils FSM. There are several important things in FSM:</p> <ul> <li><code>State</code> - any object which implements State interface</li> <li><code>StateHandler</code> (or CheckableHandlerHolder) - the handler of states</li> <li>StatesMachine - some machine which work with states and handlers</li> <li>StatesManager - simple manager that will solve which states to save and notify about states changes via its flows</li> </ul> <p><code>StatesMachine</code> have two methods:</p> <ul> <li><code>start</code> which will start work of machine</li> <li><code>startChain</code> which will add new state for handling</li> </ul> <p>The most based way to create <code>StatesMachine</code> and register <code>StateHandler</code>s looks like in the next snippet:</p> <pre><code>buildFSM<TrafficLightState> {\n strictlyOn<SomeState> {\n // state handling\n }\n}.start(CoroutineScope(...)).join()\n</code></pre> <p>Full example</p> <p> You may find full example of FSM usage in the tests of FSM in MicroUtils</p> <p>So, you must do next steps before you will launch your bot with FSM:</p> <ul> <li>Create your states. Remember that you may plan to save them, so it is likely you will need to serialize it there</li> <li>Create your handlers for your states. In most cases it is useful to use CheckableHandlerHolder if you want to use standard states machine</li> <li>Solve which states managers to use (the most simple one is the DefaultStatesManager with InMemoryDefaultStatesManager)</li> </ul>"},{"location":"tgbotapi/logic/behaviour-builder-with-fsm.html#bot-with-fsm","title":"Bot with FSM","text":"<p>There are several extensions for <code>TelegramBot</code> to create your bot with FSM:</p> <ul> <li>buildBehaviourWithFSM<ul> <li>buildBehaviourWithFSMAndStartLongPolling</li> </ul> </li> <li>telegramBotWithBehaviourAndFSM<ul> <li>telegramBotWithBehaviourAndFSMAndStartLongPolling </li> </ul> </li> </ul> <p>All of them will take as an callback some object with type CustomBehaviourContextReceiver and will looks like in the next snippet:</p> <pre><code>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</code></pre>"},{"location":"tgbotapi/logic/behaviour-builder-with-fsm.html#examples","title":"Examples","text":"<ul> <li>TelegramBotAPI-examples/FSMBot</li> <li>MicroUtils simple example in the tests</li> </ul>"},{"location":"tgbotapi/logic/behaviour-builder.html","title":"Behaviour Builder","text":"<p>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.</p>"},{"location":"tgbotapi/logic/behaviour-builder.html#main-parts-of-behaviour-builder","title":"Main parts of Behaviour Builder","text":"<p>There are several things you should know for better understanding of behaviour builder:</p> <ul> <li>BehaviourContext - it is the thing which contains all necessary tools for working with bots</li> <li>Triggers - <code>on*</code> extensions for <code>BehaviourContext</code> which allow you to create reaction on some update</li> <li>Expectations (or waiters) - <code>wait*</code> extensions which you may use in buildBehaviour function, but it is recommended to use it in bodies of triggers</li> </ul>"},{"location":"tgbotapi/logic/behaviour-builder.html#initialization","title":"Initialization","text":"<p>As was said above, there is buildBehaviour function which allow you set up your bot logic. Let\u2019s see an example:</p> <pre><code>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</code></pre>"},{"location":"tgbotapi/logic/behaviour-builder.html#filters","title":"Filters","text":"<p>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:</p> <pre><code>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</code></pre> <p>OR</p> <pre><code>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</code></pre>"},{"location":"tgbotapi/logic/behaviour-builder.html#long-polling","title":"Long polling","text":"<p>In case you wish to start long polling, you have two options:</p> <ul> <li>Start long polling with <code>buildBehaviour</code> additional functions</li> <li>Start long polling from using the result of <code>buildBehaviour</code></li> </ul> <p>More info</p> <p>More info about updates retrieving you may read at the Long Polling and Webhooks articles</p>"},{"location":"tgbotapi/logic/behaviour-builder.html#long-polling-from-buildbehaviour","title":"Long polling from <code>buildBehaviour</code>","text":"<p>With prepared bot:</p> <pre><code>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</code></pre> <p>Without prepared bot:</p> <pre><code>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</code></pre>"},{"location":"tgbotapi/logic/behaviour-builder.html#long-polling-from-the-result-of-behaviour-building","title":"Long polling from the result of behaviour building","text":"<pre><code>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</code></pre>"},{"location":"tgbotapi/logic/exceptions-handling.html","title":"Exceptions handling","text":"<p>Unfortunatelly, exceptions handling in this library is a bit difficult in some places, but that have at least two reasons: flexibility and usability.</p>"},{"location":"tgbotapi/logic/exceptions-handling.html#in-place-handling","title":"\u201cIn place\u201d handling","text":"<p>In case you know, where exceptions are happening, you may use several tools for exceptions catching:</p> <ul> <li>Catching with result</li> <li>Catching with callback</li> </ul>"},{"location":"tgbotapi/logic/exceptions-handling.html#catching-with-result","title":"Catching with result","text":"<p>If you prefer to receive <code>Result</code> objects instead of some weird callbacks, you may use the next syntax:</p> <pre><code>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</code></pre>"},{"location":"tgbotapi/logic/exceptions-handling.html#catching-with-callback","title":"Catching with callback","text":"<p>Also there is more simple (in some cases) way to handle exceptions with callbacks:</p> <pre><code>safely(\n {\n // handle error\n it.printStackTrace()\n null // return value\n }\n) {\n // do something\n}\n</code></pre>"},{"location":"tgbotapi/logic/exceptions-handling.html#bonus-different-types-of-handling","title":"Bonus: different types of handling","text":"<p>There are two types of handling:</p> <ul> <li>Just safely - when you are using something to obviously retrieve value or throw exception. When handling callback has been skipped, it will throw exception by default. For example: <pre><code>safely(\n {\n it.printStackTrace()\n \"error\"\n }\n) {\n error(\"Hi :)\") // emulate exception throwing\n \"ok\"\n} // result will be with type String\n</code></pre></li> <li>Safely without exceptions - almost the same as <code>safely</code>, but this type by default allow to return nullable value (when exception was thrown) instead of just throwing (as with <code>safely</code>): <pre><code>safelyWithouExceptions {\n // do something\n} // will returns nullable result type\n</code></pre></li> </ul>"},{"location":"tgbotapi/logic/exceptions-handling.html#global-exceptions-handling","title":"Global exceptions handling","text":"<p>The most simple way to configure exceptions handling is to change <code>CoroutineContext</code> when you are creating your <code>CoroutineScope</code> for bot processing:</p> <pre><code>val bot = telegramBot(\"TOKEN\")\n\nbot.buildBehaviour (\n scope = scope,\n defaultExceptionsHandler = {\n it.printStackTrace()\n }\n) {\n // ...\n}\n</code></pre> <p>OR</p> <pre><code>val bot = telegramBotWithBehaviour (\n \"TOKEN\",\n scope = scope,\n defaultExceptionsHandler = {\n it.printStackTrace()\n }\n) {\n // ...\n}\n</code></pre> <p>Here we have used <code>ContextSafelyExceptionHandler</code> 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.</p>"},{"location":"tgbotapi/logic/files-handling.html","title":"Files handling","text":"<p>According to the documentation there are several ways to work with files:</p> <ul> <li>By FileId</li> <li>By FileUrl (<code>typealias</code> for the <code>FileId</code>)</li> <li>By some MultipartFile (in Telegram Bot API it is multipart requests)</li> </ul>"},{"location":"tgbotapi/logic/files-handling.html#files-receiving","title":"Files receiving","text":"<p>There are several cases you may need in your app to work with files:</p> <ul> <li>Save <code>FileId</code> (for sending in future)</li> <li>Download some file into memory/file in filesystem</li> </ul>"},{"location":"tgbotapi/logic/files-handling.html#where-to-get-file-id-or-url","title":"Where to get File id or url?","text":"<p>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 <code>content</code> and then convert it to some content with media. Full code here:</p> <pre><code>val message: Message;\n\nval fileId = message.asCommonMessage() ?.withContent<MediaContent>() ?.content ?.media ?.fileId;\n</code></pre> <p>WAT? O.o</p> <p>In the code above we get some message, safely converted it to <code>CommonMessage</code> with <code>asCommonMessage</code>, then safely took its content via <code>withContent<MediaContent>() ?.content</code> and then just get its media file id.</p>"},{"location":"tgbotapi/logic/files-handling.html#download-files","title":"Download files","text":"<p>There are three ways to download files:</p> <ul> <li>Download it in memory as <code>ByteArray</code></li> <li>Take <code>ByteReadChannelAllocator</code> which allow to retrieve ByteReadChannel and do whatever you want with it</li> <li><code>[JVM Only]</code> Download it directly to file or temporal file</li> </ul>"},{"location":"tgbotapi/logic/files-handling.html#downloading-with-api-extensions","title":"Downloading with <code>API</code> extensions","text":""},{"location":"tgbotapi/logic/files-handling.html#files-jvmandroid","title":"Files (JVM/Android)","text":"<pre><code>val bot: TelegramBot;\nval fileId: FileId;\nval outputFile: File;\n\nbot.downloadFile(fileId, outputFile)\n</code></pre> <p>See downloadFile extension docs in the JVM tab to get more available options</p> <p>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:</p> <pre><code>val bot: TelegramBot;\nval fileId: FileId;\n\nval tempFile: File = bot.downloadFileToTemp(fileId)\n</code></pre> <p>See downloadFileToTemp extension docs to get more available options</p>"},{"location":"tgbotapi/logic/files-handling.html#byte-read-channel","title":"Byte read channel","text":"<pre><code>val bot: TelegramBot;\nval fileId: FileId;\n\nval bytes: ByteReadChannelAllocator = bot.downloadFileStream(fileId)\n</code></pre> <p>See downloadFileStream extension docs to get more available options</p>"},{"location":"tgbotapi/logic/files-handling.html#byte-read-channel-allocator","title":"Byte read channel allocator","text":"<pre><code>val bot: TelegramBot;\nval fileId: FileId;\n\nval bytes: ByteReadChannelAllocator = bot.downloadFileStreamAllocator(fileId)\n</code></pre> <p>See downloadFileStreamAllocator extension docs to get more available options</p>"},{"location":"tgbotapi/logic/files-handling.html#byte-arrays","title":"Byte arrays","text":"<pre><code>val bot: TelegramBot;\nval fileId: FileId;\n\nval bytes: ByteArray = bot.downloadFile(fileId)\n</code></pre> <p>See downloadFile extension docs to get more available options</p>"},{"location":"tgbotapi/logic/files-handling.html#low-level-or-how-does-it-work","title":"Low level or <code>how does it work?</code>","text":"<p>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:</p> <pre><code>val bot: TelegramBot;\nval fileId: FileId;\n\nval pathedFile: PathedFile = bot.execute(GetFile(fileId))\n\nval downloadedBytes: ByteArray = bot.execute(DownloadFile(pathedFile.filePath))\n</code></pre> <p>In the snippet above we are getting file <code>PathedFile</code> by its <code>FileId</code> and use it to download file bytes into memory using <code>DownloadFile</code> request.</p> <p>You may use almost the same way but with byte read channel allocator:</p> <pre><code>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</code></pre> <p>And then you may look into ByteReadChannel docs to get more info about what you can do with that.</p> <p>Several useful links</p> <ul> <li>GetFile</li> <li>PathedFile</li> <li>DownloadFile</li> <li>DownloadFileStream</li> </ul>"},{"location":"tgbotapi/logic/files-handling.html#files-sending","title":"Files sending","text":"<p>Of course, in most cases you must be sure that file have correct type.</p>"},{"location":"tgbotapi/logic/files-handling.html#fileid-and-fileurl","title":"FileId and FileUrl","text":"<p>It is the most simple way to send any media in Telegram, but this way have several restrictions:</p> <ul> <li>The <code>FileId</code> which has retrieved for file should not (and probably will not too) equal to the <code>FileId</code> retrieved by some other bot</li> <li>There is a chance that the file id you are using will be expired with time</li> </ul>"},{"location":"tgbotapi/logic/files-handling.html#sending-via-file","title":"Sending via file","text":"<p>JS Restrictions</p> <p> Sending via file is accessible from all supported platforms, but there is small note about <code>JS</code> - due to restrictions of work with streams and stream-like data (<code>JS</code> 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.</p> <p>Sending via file is available throw the MultipartFile. There are several wayt to get it:</p> <ul> <li>Simple creating via its constructor: <code>MultipartFile(\"filename.jpg\") { /* here Input allocation */ }</code></li> <li>Via asMultiparFile extension applicable to any <code>ByteArray</code>, <code>ByteReadChannel</code>, <code>ByteReadChannelAllocator</code> or <code>File</code> (on any platform)</li> </ul> <p>In most cases, sending via files looks like in the next snippet:</p> <pre><code>val file: File;\n\nbot.sendDocument(chatId, file.asMultipartFile())\n</code></pre>"},{"location":"tgbotapi/logic/low-level-work-with-bots.html","title":"Low-level work with bots","text":"<p>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.</p>"},{"location":"tgbotapi/logic/low-level-work-with-bots.html#base-things","title":"Base things","text":"<p>There are several important things in context of this library:</p> <ul> <li>RequestsExecutor (also \u201cknown\u201d as <code>TelegramBot</code>)</li> <li>Types</li> <li>Requests</li> </ul> <p>So, in most cases all your request calls with simplified api of this library (like <code>bot.getMe()</code>) will looks like <code>bot.execute(GetMe)</code>. 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.</p>"},{"location":"tgbotapi/logic/low-level-work-with-bots.html#how-to-handle-updates","title":"How to handle updates","text":"<p>As was written above, it will require some request:</p> <pre><code>val updates = bot.execute(GetUpdates())\n</code></pre> <p>Result type of GetUpdates request is Update. You may find inheritors of this interface in Update kdocs.</p>"},{"location":"tgbotapi/logic/low-level-work-with-bots.html#what-is-next","title":"What is next?","text":"<p>As was said above, you may look into our API extensions in case you wish to use more high-level functions instead of <code>bot.execute(SomeRequest())</code>. Besides, it will be very useful to know more about updates retrieving.</p>"},{"location":"tgbotapi/logic/media-groups.html","title":"Media Groups","text":"<p>As you know, Telegram have the feature named Media Groups. Media groups have several differences with the common messages:</p> <ul> <li>Each media group message contains special media group id</li> <li>Media group may have special caption which will be visible if only the first message of media group contains caption</li> <li>In most cases media groups came with long polling/webhooks in one pack</li> <li>Media groups can be one of three types:<ul> <li>Visual (image/video)</li> <li>Documents</li> <li>Playlists (audio)</li> </ul> </li> </ul>"},{"location":"tgbotapi/logic/media-groups.html#specific-of-media-groups-in-libraries","title":"Specific of media groups in libraries","text":"<p>Row updates</p> <p> 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</p> <p>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:</p> <pre><code>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</code></pre> <p>KDocs:</p> <ul> <li>onVisualGallery</li> <li>MediaGroupContent</li> <li>VisualMediaGroupPartContent</li> <li>MediaGroupCollectionContent.PartWrapper</li> </ul> <p>In two words, in difference with row Telegram Bot API, you will take media groups in one message instead of messages list.</p>"},{"location":"tgbotapi/logic/types-conversations.html","title":"Types conversations","text":"<p>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: </p> <p>As you may see, it is a little bit complex and require several tools for types conversation.</p>"},{"location":"tgbotapi/logic/types-conversations.html#as","title":"As","text":"<p><code>as</code> conversations will return new type in case if it is possible. For example, when you got <code>Message</code>, you may use <code>asContentMessage</code> conversation to get message with <code>content</code>:</p> <pre><code>val message: Message;\nprintln(message.asContentMessage() ?.content)\n</code></pre> <p>This code will print <code>null</code> in case when <code>message</code> is not <code>ContentMessage</code>, and <code>content</code> when is.</p>"},{"location":"tgbotapi/logic/types-conversations.html#require","title":"Require","text":"<p><code>require</code> works like <code>as</code>, but instead of returning nullable type, it will always return object with required type OR throw <code>ClassCastException</code>:</p> <pre><code>val message: Message;\nprintln(message.requireContentMessage().content)\n</code></pre> <p>This code will throw exception when message is not <code>ContentMessage</code> and print <code>content</code> when is.</p>"},{"location":"tgbotapi/logic/types-conversations.html#when","title":"When","text":"<p><code>when</code> extensions will call passed <code>block</code> when type is correct. For example:</p> <pre><code>val message: Message;\nmessage.whenContentMessage {\n println(it.content)\n}\n</code></pre> <p>Code placed above will print <code>content</code> when <code>message</code> is <code>ContentMessage</code> and do nothing when not</p>"},{"location":"tgbotapi/logic/updates-with-flows.html","title":"Updates with flows","text":"<p>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.</p>"},{"location":"tgbotapi/logic/updates-with-flows.html#phylosophy-of-flow-updates-retrieving","title":"Phylosophy of <code>Flow</code> updates retrieving","text":"<p>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:</p> <ul> <li>Create your <code>UpdatesFilter</code> (for example, with flowsUpdatesFilter factory)</li> <li>Set it up (in case of <code>flowsUpdatesFilter</code> you will set up updates handling in the lambda passed to this factory)</li> <li>Provide updates to this filter with filter#asUpdateReceiver object</li> </ul> <p>Let\u2019s look how it works with the factory above:</p> <pre><code>// 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</code></pre>"},{"location":"tgbotapi/logic/updates-with-flows.html#long-polling","title":"Long polling","text":"<p>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:</p> <pre><code>val bot = telegramBot(\"TOKEN\")\n\nbot.longPolling {\n messageFlow.onEach {\n println(it)\n }.launchIn(someCoroutineScope)\n}.join()\n</code></pre> <p>This example looks like the example above with three steps, but there are several important things here:</p> <ul> <li>You do not manage retrieving of updates by hands</li> <li><code>.join()</code> will suspend your function \ud83d\ude0a <code>longPolling</code> function returns <code>Job</code> and you may use it to:</li> <li><code>cancel</code> working of long polling (just call <code>job.cancel()</code>)</li> <li><code>join</code> and wait while the work of <code>longPolling</code> will not be completed (it will works infinity if you will not cancel it anywhere)</li> <li>FlowsUpdatesFilter has been created under the hood of <code>longPolling</code> function</li> </ul>"},{"location":"tgbotapi/logic/updates-with-flows.html#results-and-what-is-next","title":"Results and <code>What is next?</code>","text":"<p>As a result you can start listen updates and react on it. Next recommended articles:</p> <ul> <li>Behaviour Builder as a variant of asynchronous handling of your bot logic</li> <li>FSM variant of Behaviour Builder</li> </ul>"},{"location":"tgbotapi/updates/heroku.html","title":"Heroku","text":"<p>Preview reading</p> <p>It is recommended to visit our pages about UpdatesFilters and Webhooks to have more clear understanding about what is happening in this examples page</p> <p>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:</p> <ul> <li>Heroku apps by default accessible via <code>https://<app name>.herokuapp.com/</code></li> <li>Heroku provide one port to be proxied for the link above. You can retrieve number of this port by calling <code>System.getenv(\"PORT\").toInt()</code></li> <li>Currently (<code>Sat Aug 15 5:04:21 +00 2020</code>) there is only one official server engine for ktor which is correctly working with Heroku: Tomcat server engine</li> </ul> <p>Server configuration alternatives</p> <p> 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</p>"},{"location":"tgbotapi/updates/heroku.html#short-example-with-behaviour-builder","title":"Short example with Behaviour Builder","text":"<pre><code>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</code></pre>"},{"location":"tgbotapi/updates/heroku.html#configuration-example-without-behaviour-builder","title":"Configuration example without Behaviour Builder","text":"<pre><code>// 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</code></pre>"},{"location":"tgbotapi/updates/long-polling.html","title":"Long polling","text":"<p>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.</p>"},{"location":"tgbotapi/updates/long-polling.html#related-topics","title":"Related topics","text":"<ul> <li>Updates filters</li> </ul>"},{"location":"tgbotapi/updates/long-polling.html#long-polling-in-this-library","title":"Long polling in this library","text":"<p>There are a lot of ways to include work with long polling:</p> <ul> <li><code>RequestsExecutor#longPollingFlow</code> Is the base way to get all updates cold Flow. Remember, that this flow will not be launched automatically<ul> <li><code>RequestsExecutor#startGettingOfUpdatesByLongPolling</code> Old and almost deprecated way</li> <li><code>RequestsExecutor#longPolling</code> Works like <code>startGettingOfUpdatesByLongPolling</code> but shorted in a name :)</li> </ul> </li> <li><code>RequestsExecutor#createAccumulatedUpdatesRetrieverFlow</code> Works like <code>longPollingFlow</code>, but flow inside will return only the updates accumulated at the moment of calls (all new updates will not be passed throw this flow)<ul> <li><code>RequestsExecutor#retrieveAccumulatedUpdates</code> Use <code>createAccumulatedUpdatesRetrieverFlow</code> to perform all accumulated updates</li> <li><code>RequestsExecutor#flushAccumulatedUpdates</code> Works like <code>retrieveAccumulatedUpdates</code> but perform all updates directly in a place of calling</li> </ul> </li> <li>By yourself with <code>GetUpdates</code> request or <code>RequestsExecutor#getUpdates</code> extension</li> </ul>"},{"location":"tgbotapi/updates/long-polling.html#longpolling","title":"longPolling","text":"<p><code>longPolling</code> is a simple way to start getting updates and work with bot:</p> <pre><code>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</code></pre>"},{"location":"tgbotapi/updates/long-polling.html#startgettingofupdatesbylongpolling","title":"startGettingOfUpdatesByLongPolling","text":"<p>The main aim of <code>startGettingOfUpdatesByLongPolling</code> extension was to provide more simple way to get updates in automatic mode:</p> <pre><code>val bot = telegramBot(token)\nbot.startGettingOfUpdatesByLongPolling(\n {\n println(it) // will be printed each update from chats with messages\n }\n)\n</code></pre> <p>The other way is to use the most basic <code>startGettingOfUpdatesByLongPolling</code> extension:</p> <pre><code>val bot = telegramBot(token)\nbot.startGettingOfUpdatesByLongPolling {\n println(it) // will be printed each update\n}\n</code></pre>"},{"location":"tgbotapi/updates/long-polling.html#see-also","title":"See also","text":"<ul> <li>Webhooks</li> <li>Updates filters</li> </ul>"},{"location":"tgbotapi/updates/updates-filters.html","title":"Updates filters","text":"<p>Due to the fact, that anyway you will get updates in one format (<code>Update</code> objects), some time ago was solved to create one point of updates filters for more usefull way of updates handling</p>"},{"location":"tgbotapi/updates/updates-filters.html#updatesfilter","title":"UpdatesFilter","text":"<p><code>UpdatesFilter</code> currently have two properties:</p> <ul> <li><code>asUpdateReceiver</code> - required to represent this filter as common updates receiver which able to get any <code>Update</code></li> <li><code>allowedUpdates</code> - required to determine, which updates are usefull for this filter</li> </ul> <p>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).</p>"},{"location":"tgbotapi/updates/updates-filters.html#simpleupdatesfilter","title":"SimpleUpdatesFilter","text":"<p><code>SimpleUpdatesFilter</code> is a simple variant of filters. It have a lot of <code>UpdateReceiver</code> 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:</p> <pre><code>SimpleUpdatesFilter {\n println(it)\n}\n</code></pre>"},{"location":"tgbotapi/updates/updates-filters.html#flowsupdatesfilter","title":"FlowsUpdatesFilter","text":"<p>A little bit more modern way is to use <code>FlowsUpdatesFilter</code>. It is very powerfull API of Kotlin Coroutines Flows, built-in support of additional extensions for <code>FlowsUpdatesFilter</code> and <code>Flow<...></code> receivers and opportunity to split one filter for as much receivers as you want. Filter creating example:</p> <pre><code>val scope = CoroutineScope(Dispatchers.Default)\nflowsUpdatesFilter {\n messageFlow.onEach {\n println(it)\n }.launchIn(scope)\n}\n</code></pre>"},{"location":"tgbotapi/updates/updates-filters.html#combining-of-flows","title":"Combining of flows","text":"<p>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:</p> <ul> <li>Standard <code>plus</code> operation and handling of different flows: <pre><code>flowsUpdatesFilter {\n (messageFlow + channelPostFlow).onEach {\n println(it) // will be printed each message update from channels and chats both\n }.launchIn(scope)\n}\n</code></pre></li> <li>TelegramBotAPI library support function <code>aggregateFlows</code>: <pre><code>flowsUpdatesFilter {\n aggregateFlows(\n scope,\n messageFlow,\n channelPostFlow\n ).onEach {\n println(it) // will be printed each message update from channels and chats both\n }.launchIn(scope)\n}\n</code></pre></li> <li><code>FlowsUpdatesFilter</code> extensions: <pre><code>flowsUpdatesFilter {\n allSentMessagesFlow.onEach {\n println(it) // will be printed each message update from channels and chats both\n }.launchIn(scope)\n}\n</code></pre></li> </ul>"},{"location":"tgbotapi/updates/updates-filters.html#types-filtering","title":"Types filtering","text":"<p><code>FlowsUpdatesFilter</code> have a lot of extensions for messages types filtering:</p> <pre><code>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</code></pre> <p>The same things were created for media groups:</p> <pre><code>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</code></pre> <p>Besides, there is an opportunity to avoid separation on media groups and common messages and receive photos and videos content in one flow:</p> <pre><code>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</code></pre>"},{"location":"tgbotapi/updates/updates-filters.html#see-also","title":"See also","text":"<ul> <li>Long polling</li> <li>Webhooks</li> </ul>"},{"location":"tgbotapi/updates/webhooks.html","title":"Webhooks","text":"<p>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:</p> <ul> <li><code>Route#includeWebhookHandlingInRoute</code> for ktor server</li> <li><code>Route#includeWebhookHandlingInRouteWithFlows</code> </li> <li><code>startListenWebhooks</code></li> <li><code>RequestsExecutor#setWebhookInfoAndStartListenWebhooks</code></li> </ul>"},{"location":"tgbotapi/updates/webhooks.html#setwebhookinfoandstartlistenwebhooks","title":"<code>setWebhookInfoAndStartListenWebhooks</code>","text":"<p>It is the most common way to set updates webhooks and start listening of them. Example:</p> <pre><code>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</code></pre> <p>If you will use previous example, ktor server will bind and listen url <code>0.0.0.0:8080/subroute</code> and telegram will send requests to address <code>address.com/webhook_route</code> with custom certificate. Alternative variant will use the other <code>SetWebhook</code> request variant:</p> <pre><code>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</code></pre> <p>As a result, request <code>SetWebhook</code> will be executed and after this server will start its working and handling of updates.</p>"},{"location":"tgbotapi/updates/webhooks.html#startlistenwebhooks","title":"<code>startListenWebhooks</code>","text":"<p>This function is working almost exactly like previous example, but this one will not set up webhook info in telegram:</p> <pre><code>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</code></pre> <p>The result will be the same as in previous example: server will start its working and handling of updates on <code>0.0.0.0:8080/subroute</code>. 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.</p>"},{"location":"tgbotapi/updates/webhooks.html#extensions-includewebhookhandlinginroute-and-includewebhookhandlinginroutewithflows","title":"Extensions <code>includeWebhookHandlingInRoute</code> and <code>includeWebhookHandlingInRouteWithFlows</code>","text":"<p>For these extensions you will need to start your server manualy. In common case it will look like:</p> <pre><code>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</code></pre> <p>In the example above server will started and binded for listening on <code>0.0.0.0:8080</code>.</p>"},{"location":"tgbotapi/updates/webhooks.html#see-also","title":"See also","text":"<ul> <li>Updates filters</li> <li>Long polling</li> </ul>"}]} |