diff --git a/404.html b/404.html index 5ba3502..ea30081 100644 --- a/404.html +++ b/404.html @@ -361,6 +361,8 @@ + + @@ -403,6 +405,20 @@ +
Hello :) It is my libraries docs place and I glad to welcome you here. I hope, this documentation place will help you.
flowchart RL\n KSLog[<a href='https://github.com/InsanusMokrassar/kslog'>KSLog</a>]\n MicroUtils[<a href='https://github.com/InsanusMokrassar/MicroUtils'>MicroUtils</a>]\n TelegramBotAPI[<a href='https://github.com/InsanusMokrassar/ktgbotapi'>TelegramBotAPI</a>]\n TelegramBotAPI-examples[<a href='https://github.com/InsanusMokrassar/TelegramBotAPI-examples'>TelegramBotAPI-examples </a>]\n PlaguBot[<a href='https://github.com/InsanusMokrassar/PlaguBot'>PlaguBot</a>]\n TelegramBotAPILibraries[<a href='https://github.com/InsanusMokrassar/TelegramBotAPILibraries'>TelegramBotAPILibraries</a>]\n PlaguBotPlugins[<a href='https://github.com/InsanusMokrassar/PlaguBotPlugins'>PlaguBotPlugins</a>]\n PlaguBotExample[<a href='https://github.com/InsanusMokrassar/PlaguBotExample'>PlaguBotExample</a>]\n BooruGrabberTelegramBot[<a href='https://github.com/InsanusMokrassar/BooruGrabberTelegramBot'>BooruGrabberTelegramBot</a>]\n SauceNaoTelegramBot[<a href='https://github.com/InsanusMokrassar/SauceNaoTelegramBot'>SauceNaoTelegramBot</a>]\n PlaguPoster[<a href='https://github.com/InsanusMokrassar/PlaguPoster'>PlaguPoster</a>]\n PlaguBotSuggestionsBot[<a href='https://github.com/InsanusMokrassar/PlaguBotSuggestionsBot'>PlaguBotSuggestionsBot</a>]\n TelegramBotTutorial[<a href='https://github.com/InsanusMokrassar/TelegramBotTutorial'>TelegramBotTutorial</a>]\n Krontab[<a href='https://github.com/InsanusMokrassar/krontab'>Krontab</a>]\n KJSUiKit[<a href='https://github.com/InsanusMokrassar/JSUiKitKBindings'>KJSUiKit</a>]\n SauceNaoAPI[<a href='https://github.com/InsanusMokrassar/SauceNaoAPI'>SauceNaoAPI</a>]\n Navigation[<a href='https://github.com/InsanusMokrassar/navigation'>Navigation</a>]\n\n TelegramBotAPI-bot_template[<a href='https://github.com/InsanusMokrassar/TelegramBotAPI-bot_template'>TelegramBotAPI-bot_template</a>]\n PlaguBotPluginTemplate[<a href='https://github.com/InsanusMokrassar/PlaguBotPluginTemplate'>PlaguBotPluginTemplate</a>]\n PlaguBotBotTemplate[<a href='https://github.com/InsanusMokrassar/PlaguBotBotTemplate'>PlaguBotBotTemplate</a>]\n\n MicroUtils --> KSLog\n TelegramBotAPI --> MicroUtils\n TelegramBotAPI-examples --> TelegramBotAPI\n PlaguBot --> TelegramBotAPI\n TelegramBotAPILibraries --> PlaguBot\n PlaguBotPlugins --> TelegramBotAPILibraries\n PlaguBotExample --> PlaguBotPlugins\n BooruGrabberTelegramBot --> TelegramBotAPI\n BooruGrabberTelegramBot --> Krontab\n SauceNaoTelegramBot --> TelegramBotAPI\n SauceNaoTelegramBot --> SauceNaoAPI\n TelegramBotTutorial --> PlaguBotPlugins\n PlaguBotSuggestionsBot --> PlaguBotPlugins\n PlaguPoster --> PlaguBotPlugins\n PlaguPoster --> Krontab\n SauceNaoAPI --> MicroUtils\n Navigation --> MicroUtils\n\n TelegramBotAPI-bot_template -.- TelegramBotAPI\n PlaguBotPluginTemplate -.- PlaguBot\n PlaguBotBotTemplate -.- PlaguBot
Library was created to give oppotunity to launch some things from time to time according to some schedule in runtime of applications.
There are several ways to configure and use this library:
Anyway, to start some action from time to time you will need to use one of extensions/functions:
val kronScheduler = /* creating of KronScheduler instance */;\nkronScheduler.doWhile {\n// some action\ntrue // true - repeat on next time\n}\n
If you want to include krontab in your project, just add next line to your dependencies part:
krontab
implementation \"dev.inmo:krontab:$krontab_version\"\n
Next version is the latest currently for the library:
For old version of Gradle, instead of implementation word developers must use compile.
implementation
compile
Developers can use more simple way to configure repeat times is string. String configuring like a crontab, but with a little bit different meanings:
crontab
/--------------- Seconds\n| /------------- Minutes\n| | /----------- Hours\n| | | /--------- Days of months\n| | | | /------- Months\n| | | | | /----- (optional) Year\n| | | | | | /--- (optional) Timezone offset\n| | | | | | | / (optional) Week days\n* * * * * * 0o *w\n
It is different with original crontab syntax for the reason, that expected that in practice developers will use seconds and minutes with more probability than months (for example) or even years. In fact, developers will use something like:
doWhile(\"/5 * * * *\") {\nprintln(\"Called\")\ntrue // true - repeat on next time\n}\n
An other version:
doInfinity(\"/5 * * * *\") {\nprintln(\"Called\")\n}\n
Both of examples will print Called message every five seconds.
Called
Also, this library currently supports DSL for creating the same goals:
val kronScheduler = buildSchedule {\nseconds {\nfrom (0) every 5\n}\n}\nkronScheduler.doWhile {\nprintln(\"Called\")\ntrue // true - repeat on next time\n}\n
Or
val kronScheduler = buildSchedule {\nseconds {\n0 every 5\n}\n}\nkronScheduler.doWhile {\nprintln(\"Called\")\ntrue // true - repeat on next time\n}\n
val kronScheduler = buildSchedule {\nseconds {\n0 every 5\n}\n}\nkronScheduler.doInfinity {\nprintln(\"Called\")\n}\n
All of these examples will do the same things: print Called message every five seconds.
With regular doOnce/doWhile/doInfinity there are two types of their variations: local and timezoned. Local variations (doOnceLocal/doWhileLocal/doInfinityLocal) will pass DateTime as an argument into the block:
doOnce
doWhile
doInfinity
doOnceLocal
doWhileLocal
doInfinityLocal
DateTime
doInfinityLocal(\"/5 * * * *\") {\nprintln(it) // will print current date time\n}\n
Timezoned variations (doOnceTz/doWhileTz/doInfinityTz) will do the same thing but pass as an argument DateTimeTz:
doOnceTz
doWhileTz
doInfinityTz
DateTimeTz
doInfinityTz(\"/5 * * * * 0o\") {\nprintln(it) // will print current date time in UTC\n}\n
It is useful in cases when you need to get the time of calling and avoid extra calls to system time.
KronScheduler
*Here there is an important notice, that Work infinity is not exactly infinity. Actually, that means that do while coroutine is alive and in fact executing will be stopped when coroutine became cancelled.
Work infinity
infinity
do while coroutine is alive
Any KronSchedulercan e converted to a Flow<DateTime using extension asFlow:
Flow<DateTime
asFlow
val kronScheduler = buildSchedule {\nseconds {\n0 every 1\n}\n}\nval flow = kronScheduler.asFlow()\n
So, in this case any operations related to flow are available and it is expected that they will work correctly. For example, it is possible to use this flow with takeWhile:
takeWhile
flow.takeWhile {\ncondition()\n}.collect {\naction()\n}\n
Offsets in this library works via passing parameter ending with o in any place after month config. Currently there is only one format supported for offsets: minutes of offsets. To use time zones you will need to call next method with DateTimeTz argument or nextTimeZoned method with any KronScheduler instance, but in case if this scheduler is not instance of KronSchedulerTz it will work like you passed just DateTime.
o
month
next
nextTimeZoned
KronSchedulerTz
Besides, in case you wish to use time zones explicitly, you will need to get KronSchedulerTz. It is possible by:
createSimpleScheduler
buildSchedule
KrontabTemplate#toSchedule
KrontabTemplate#toKronScheduler
defaultOffset
SchedulerBuilder#build
Unlike original CRON, here week days:
AND
0-3w
0,1,2,3w
KronScheduler is the simple interface with only one function next. This function optionally get as a parameter DateTime which will be used as start point for the calculation of next trigger time. This function will return the next DateTime when something must happen.
Default realisation (CronDateTimeScheduler) can be created using several ways:
CronDateTimeScheduler
SchedulerBuilder
In the examples below the result of created scheduler will be the same.
Crontab-like syntax
See String format for more info about the crontab-line syntax
This way will be very useful for cases when you need to configure something via external configuration (from file on startup or via some parameter from requests, for example):
val schedule = \"5 * * * *\"\nval scheduler = buildSchedule(schedule)\nscheduler.asFlow().onEach {\n// this block will be called every minute at 5 seconds\n}.launchIn(someCoroutineScope)\n
In case of usage builder (lets call it lambda way), you will be able to configure scheduler in more type-safe way:
lambda way
val scheduler = buildSchedule {\nseconds {\nat(5)\n}\n}\nscheduler.asFlow().onEach {\n// this block will be called every minute at 5 seconds\n}.launchIn(someCoroutineScope)\n
You are always able to use your own realisation of scheduler. For example:
class RandomScheduler : KronScheduler {\noverride suspend fun next(relatively: DateTime): DateTime {\nreturn relatively + DateTimeSpan(seconds = Random.nextInt() % 60)\n}\n}\n
In the example above we have created RandomScheduler, which will return random next time in range 0-60 seconds since relatively argument.
RandomScheduler
0-60
relatively
As in crontab util, this library have almost the same format of string:
Int
w
ms
0
*/15
30
22
*/5
11
60o
0w
*/2w
4w
0ms
*/150ms
300ms
Example with almost same description:
/-------------------- (0-59) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Seconds\n| /------------------ (0-59) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Minutes\n| | /---------------- (0-23) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Hours\n| | | /-------------- (0-30) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Days of months\n| | | | /------------ (0-11) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Months\n| | | | | /---------- (optional, any int) Year\n| | | | | | /-------- (optional) \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7 Timezone offset\n| | | | | | | /----- (optional, 0-6) \u00b7\u00b7\u00b7 Week days\n| | | | | | | | /-- (optional, 0-999) \u00b7 Milliseconds (0 by default)\n* * * * * * 0o *w 0ms\n
Years, timezone, week days and milliseconds are optional settings. Next snippets are equal:
*/15 * * * *\n*/15 * * * * * // with year\n*/15 * * * * * 0ms // with year and milliseconds\n
Currently the library support next syntax for date/time elements:
{int}-{int}
{int}/{int}
*/{int}
{int}
{other_element},{other_element}
F
f
L
l
Ranges are working like common rangeTo (or ..) in kotlin:
rangeTo
..
0-5 * * * *\n
In the example above scheduler will trigger every second from the beginning of the minute up to fifth second of minute.
Start/step is a little bit more complicated syntax. It means start from the first element, repeat triggering every second element. Examples:
start from the first element, repeat triggering every second element
5/15 * * * *\n
Means that each minute starting from fifth second it will repeat triggering every fifteenth second: 5, 20, 35, 50.
5, 20, 35, 50
Every is more simple syntax and could be explained as a shortcut for 0/{int}. Example:
0/{int}
*/15 * * * *\n
Means that each minute it will repeat triggering every fifteenth second: 0, 15, 30, 45.
0, 15, 30, 45
The most simple syntax. It means, that scheduler will call triggering every time when element was reached:
15 * * * *\n
Means that each minute scheduler will call triggering at the fifteenth second.
All the previous elements can be combined with listing. Lets just see several examples:
0,10 * * * *\n
Will trigger every minute at the 0 and 10 seconds (see Just at the time)
10
0-5,10 * * * *\n
Will trigger every minute from 0 to 5 seconds and at the 10 seconds (see Ranges)
5
0/5 * * * *
0/5,L * * * *
0/15 30 * * *
0/15 30 * * * 500ms
1 2 3 F,4,L 5
1 2 3 F,4,L 5 60o
1 2 3 F,4,L 5 60o 0-2w
1 2 3 F,4,L 5 2021
1 2 3 F,4,L 5 2021 60o
1 2 3 F,4,L 5 2021 60o 0-2w
1 2 3 F,4,L 5 2021 60o 0-2w 500ms
Not very often. It depend on libraries (coroutines, korlibs/klock) updates and on some new awesome, but lightweight, features coming.
First of all, this library will be useful for long uptime applications which have some tasks to do from time to time.
In two words, you should call buildSchedule or createSimpleScheduler:
buildSchedule(\"5 * * * *\").asFlow().collect { /* do something */ }\n
You can read more about syntax in String format section.
Custom KronScheduler
You always able to create your own scheduler. In this section will be presented different ways and examples around standard CronDateTimeScheduler builders buildSchedule. You can read about schedulers in KrontabScheduler
Currently, buildSchedule is the recommended start point for every scheduler. Usually, it is look like:
val scheduler = buildSchedule(\"5 * * * *\")\n
Or:
val scheduler = buildSchedule {\nseconds {\nat(5)\n}\n}\n
On the top of any KronScheduler currently there are several groups of extensions:
All executes are look like do.... All executes are described below:
do...
block
true
Shortcuts are the constants that are initializing in a lazy way to provide preset KronSchedulers. For more info about KrontabScheduler you can read its own page.
KrontabScheduler
AnyTimeScheduler
Every*Scheduler
EverySecondScheduler
EveryMinuteScheduler
EveryHourScheduler
EveryDayOfMonthScheduler
EveryMonthScheduler
EveryYearScheduler
Here currently there is only one extension for KronScheduler: KronScheduler#asFlow. As a result you will get Flow<DateTime> (in fact SchedulerFlow) which will trigger next emit on each not null next DateTime
KronScheduler#asFlow
Flow<DateTime>
SchedulerFlow
emit
In two words, you must add dependency dev.inmo:krontab:$krontab_version to your project. The latest version presented by next badge:
dev.inmo:krontab:$krontab_version
To use this library, you will need to include MavenCentral repository in you project
MavenCentral
mavenCentral()\n
Next snippets must be placed into your dependencies part of build.gradle (for gradle) or pom.xml (for maven).
dependencies
build.gradle
pom.xml
<dependency>\n<groupId>dev.inmo</groupId>\n<artifactId>krontab</artifactId>\n<version>${krontab_version}</version>\n</dependency>\n
It is simple and easy-to-use tool for logging on the most popular platforms in Kotlin Multiplatform:
By default, KSLog is using built-in tools for logging on each supported platform:
java.util.logging.Logger
JVM
android.util.Log
Android
Console
JS
But you always may create your logger and customize as you wish:
KSLog.default = KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->\n// do your logging\n}\n
This library also supports native targets in experimental mode. By default, all native targets will use simple printing in the console
Just use some boring extensions like:
KSLog.i(\"Some message\")\n// OR\nKSLog.i(\"Some tag\", \"Some message\")\n// OR\nKSLog.i(\"Some tag\", \"Some message\", IllegalArgumentException(\"So, that is exception :)\"))\n// OR\nKSLog.i(\"Some optional tag\", Exception(\"Optional\")) { \"Lazy inited message\" }\n// OR\nKSLog.iS(\"Some optional tag\", Exception(\"Optional\")) { \"Lazy inited message for suspendable calculation of text\" }\n// OR EVEN\nKSLog.l(LogLevel.INFO, \"Some tag\", \"Some message\", IllegalArgumentException(\"So, that is exception :)\"))\n// OR\nKSLog.l(LogLevel.INFO, \"Some optional tag\", IllegalArgumentException(\"So, that is exception :)\")) { \"And lazily inited message\" }\n
There are several important \u201cterms\u201d in context of this library:
KSLog.default
KSLog
KSLog.i
KSLog.info
Any.logger
apply
Every logging extension (like KSLog.i) have its analog with lazy inited message text and the same one with suffix S (like KSLog.iS) for the suspendable message calculation.
S
KSLog.iS
Default logger can be created by passing defaultTag and one of variants log level filters: set or minimal loggable level. In JVM you also may setup any logger as base logger for default realizations of KSLog. Besides, you may use your own callback (on any target platform) as output of logging:
defaultTag
val logger = KSLog { logLevel, optionalTag, message, optionalThrowable ->\nprintln(\"[$logLevel] $optionalTag - $message: $optionalThrowable.stackTraceToString()\")\n}\n
In the example above we will take the logger which will just print incoming data as common output.
logger
implementation \"dev.inmo:kslog:$kslog_version\"\n
<dependency>\n<groupId>dev.inmo</groupId>\n<artifactId>kslog</artifactId>\n<version>${kslog_version}</version>\n</dependency>\n
Message type notice
On this page all the messages will be just simple String, but you may pass any object as the message
String
As has been said in the setup section, this library contains next levels of logging with their default representations on each platform:
Each of these levels have fullname and shortname shortcat extensions:
KSLog.debug
KSLog.d
KSLog.dS
KSLog.verbose
KSLog.v
KSLog.vS
KSLog.warning
KSLog.w
KSLog.wS
KSLog.error
KSLog.e
KSLog.eS
KSLog.assert
KSLog.wtf
KSLog.wtfS
And any of these shortcuts may accept one of several arguments combinations:
suspendable
So, when you want to log some expected exception, there are three common ways to do it:
val logger = KSLog.default\n// with callback\nlogger.info(tag, throwable) {\n\"Some your message for this event\"\n}\n// with suspendable callback\nlogger.infoS(tag, throwable) {\nwithContext(Dispatchers.Default) {\n\"Some your message for this event\"\n}\n}\n// Just with message\nlogger.info(\"Some your message for this event\", throwable)\n// With message and tag as strings\nlogger.info(tag, \"Some your message for this event\", throwable)\n
Of course, any of this calls can be shortenned:
val logger = KSLog.default\n// with callback\nlogger.i(tag, throwable) {\n\"Some your message for this event\"\n}\n// with suspendable callback\nlogger.iS(tag, throwable) {\nwithContext(Dispatchers.Default) {\n\"Some your message for this event\"\n}\n}\n// Just with message\nlogger.i(\"Some your message for this event\", throwable)\n// With message and tag as strings\nlogger.i(tag, \"Some your message for this event\", throwable)\n
There is special shortcat - for base performLog. In that case the only change is that you will require to pass the LogLevel more obviously:
performLog
LogLevel
val logger = KSLog.default\n// with callback\nlogger.log(LogLevel.INFO, tag, throwable) {\n\"Some your message for this event\"\n}\n// with suspendable callback\nlogger.logS(LogLevel.INFO, tag, throwable) {\nwithContext(Dispatchers.Default) {\n\"Some your message for this event\"\n}\n}\n// Just with message\nlogger.log(LogLevel.INFO, \"Some your message for this event\", throwable)\n// With message and tag as strings\nlogger.log(LogLevel.INFO, tag, \"Some your message for this event\", throwable)\n
OR
val logger = KSLog.default\n// with callback\nlogger.l(LogLevel.INFO, tag, throwable) {\n\"Some your message for this event\"\n}\n// with suspendable callback\nlogger.lS(LogLevel.INFO, tag, throwable) {\nwithContext(Dispatchers.Default) {\n\"Some your message for this event\"\n}\n}\n// Just with message\nlogger.l(LogLevel.INFO, \"Some your message for this event\", throwable)\n// With message and tag as strings\nlogger.l(LogLevel.INFO, tag, \"Some your message for this event\", throwable)\n
implementation(\"dev.inmo:kslog:$kslog_version\")\n
The main point in setup in your code is to setup default logger:
KSLog.default = KSLog(\"defaultTag\")\n
You may use custom messageFormatter in any of KSLog factory to customize output of KSLog logging. For example:
messageFormatter
KSLog(\n\"loggingWithCustomFormat\",\nmessageFormatter = { level, tag, message, throwable ->\nprintln(\"[$level] $tag - $message: $throwable\")\n}\n)\n
Additionally you may use one of several different settings:
minLoggingLevel
levels
firstLevel
secondLevel
otherLevels
vararg
In case you are passing minLoggingLevel, the level and more important levels will be passed to logs. For example, when you are settings up your logger as in next snippet:
val logger = KSLog(\n\"exampleTag\",\nminLoggingLevel = LogLevel.INFO\n)\n
The next levels will be logged with logger:
INFO
WARNING
ERROR
ASSERT
It is logger which will call incoming performLogCallback on each logging. This logger can be create simply with one callback:
performLogCallback
KSLog { level, tag, message, throwable ->\nprintln(\"[$level] $tag - $message: $throwable\")\n}\n
It is simple value class which can be used for zero-cost usage of some tag and calling for KSLog.default. For example, if you will create tag logger with next code:
val logger = TagLogger(\"tagLoggerTag\")\n
The logger will call KSLog.default with the tag tagLoggerTag on each calling of logging.
tagLoggerTag
This pretty simple logger will call its fallbackLogger only in cases when incoming messageFilter will return true for logging:
fallbackLogger
messageFilter
val baseLogger = KSLog(\"base\") // log everything with the tag `base` if not set other\nval filtered = baseLogger.filtered { _, t, _ ->\nt == \"base\"\n}\n
In the example above baseLogger will perform logs in two ways: when it has been called directly or when we call log performing with the tag \"base\" or null. Besides, you can see there extension filtered which allow to create FilterKSLog logger with simple lambda.
baseLogger
\"base\"
null
filtered
FilterKSLog
This logger accepts map of types with the target loggers. You may build this logger with the special simple DSL:
val baseLogger = KSLog(\"base\") // log everything with the tag `base` if not set other\nval typed = buildTypedLogger {\non<Int>(baseLogger) // log all ints to the baseLogger\non<Float> { _, _, message, _ ->// log all floats to the passed logger\nprintln(message.toString()) // just print all floats\n}\ndefault { level, tag, message, throwable ->\nKSLog.performLog(level, tag, message, throwable)\n}\n}\n
There are two things which can be useful in your code: logger and logTag extensions. logTag is the autocalculated by your object classname tag. logger extension can be used with applying to any object like in the next snippet:
logTag
class SomeClass {\ninit {\nlogger.i(\"inited\")\n}\n}\n
The code above will trigger calling of logging in KSLog.default with level LogLevel.INFO using tag SomeClass and message \"inited\". As you could have guessed, logger is using TagLogger with logTag underhood and the most expensive operation here is automatical calculation of logTag.
LogLevel.INFO
SomeClass
\"inited\"
TagLogger
For JVM you may setup additionally use java loggers as the second parameter of KSLog factory. For example:
KSLog(\n\"yourTag\"\nLogger.getLogger(\"YourJavaLoggerName\")\n)\n
Hello! This is a set of libraries for working with Telegram Bot API.
There are several things you need to do to launch examples below:
mavenCentral()
implementation \"dev.inmo:tgbotapi:$tgbotapi_version\"
tgbotapi_version
More including instructions available here. Other configuration examples:
suspend fun main() {\nval bot = telegramBot(TOKEN)\nbot.buildBehaviourWithLongPolling {\nprintln(getMe())\nonCommand(\"start\") {\nreply(it, \"Hi:)\")\n}\n}.join()\n}\n
In this example you will see information about this bot at the moment of starting and answer with Hi:) every time it gets message /start
Hi:)
/start
suspend fun main() {\nval bot = telegramBot(TOKEN)\nval flowsUpdatesFilter = FlowsUpdatesFilter()\nbot.buildBehaviour(flowUpdatesFilter = flowsUpdatesFilter) {\nprintln(getMe())\nonCommand(\"start\") {\nreply(it, \"Hi:)\")\n}\nretrieveAccumulatedUpdates(this).join()\n}\n}\n
The main difference with the previous example is that bot will get only last updates (accumulated before bot launch and maybe some updates it got after launch)
suspend fun main() {\nval bot = telegramBot(TOKEN)\nbot.buildBehaviourWithLongPolling {\nprintln(getMe())\nval nameReplyMarkup = ReplyKeyboardMarkup(\nmatrix {\nrow {\n+SimpleKeyboardButton(\"nope\")\n}\n}\n)\nonCommand(\"start\") {\nval photo = waitPhoto(\nSendTextMessage(it.chat.id, \"Send me your photo please\")\n).first()\nval name = waitText(\nSendTextMessage(\nit.chat.id,\n\"Send me your name or choose \\\"nope\\\"\",\nreplyMarkup = nameReplyMarkup\n)\n).first().text.takeIf { it != \"nope\" }\nsendPhoto(\nit.chat,\nphoto.mediaCollection,\nentities = buildEntities {\nif (name != null) regular(name) // may be collapsed up to name ?.let(::regular)\n}\n)\n}\n}.join()\n}\n
You may find examples in this project. Besides, you are always welcome in our chat.
In the telegram system there are two types of keyboards:
Low-level way to create keyboard looks like in the next snippet:
ReplyKeyboardMarkup(\nmatrix {\nrow {\nadd(SimpleKeyboardButton(\"Simple text\"))\n// ...\n}\n// ...\n}\n)\n
In case you wish to create inline keyboard, it will look like the same as for reply keyboard. But there is another way. The next snippet will create the same keyboard as on the screenshots above:
// reply keyboard\nreplyKeyboard {\nrow {\nsimpleButton(\"7\")\nsimpleButton(\"8\")\nsimpleButton(\"9\")\nsimpleButton(\"*\")\n}\nrow {\nsimpleButton(\"4\")\nsimpleButton(\"5\")\nsimpleButton(\"6\")\nsimpleButton(\"/\")\n}\nrow {\nsimpleButton(\"1\")\nsimpleButton(\"2\")\nsimpleButton(\"3\")\nsimpleButton(\"-\")\n}\nrow {\nsimpleButton(\"0\")\nsimpleButton(\".\")\nsimpleButton(\"=\")\nsimpleButton(\"+\")\n}\n}\n// inline keyboard\ninlineKeyboard {\nrow {\ndataButton(\"Get random music\", \"random\")\n}\nrow {\nurlButton(\"Send music to friends\", \"https://some.link\")\n}\n}\n
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:
In the Bot API there is no independent sendLiveLocation method, instead it is suggested to use sendLocation with setting up live_period. In this library in difference with original Bot API live location is special request. It was required because of in fact live locations and static locations are different types of location info and you as bot developer may interact with them differently.
sendLiveLocation
live_period
Anyway, in common case the logic looks like:
In difference with sendLiveLocation, startLiveLocation using LiveLocationProvider. With this provider you need not to handle chat and message ids and keep some other data for location changes. Instead, you workflow with provider will be next:
Besides, LiveLocationProvider contains different useful parameters about live location
LiveLocationProvider
This way of live locations handling is based on coroutines Flow and allow you to pass some external Flow with EditLiveLocationInfo. So, workflow:
Flow
flow {\nvar i = 0\nwhile (isActive) {\nval newInfo = EditLiveLocationInfo(\nlatitude = i.toDouble(),\nlongitude = i.toDouble(),\nreplyMarkup = flatInlineKeyboard {\ndataButton(\"Cancel\", \"cancel\")\n}\n)\nemit(newInfo)\ni++\ndelay(10000L) // 10 seconds\n}\n}\n
val currentMessageState = MutableStateFlow<ContentMessage<LocationContent>?>(null)\n
handleLiveLocation(\nit.chat.id,\nlocationsFlow,\nsentMessageFlow = FlowCollector { currentMessageState.emit(it) }\n)\n// this code will be called after `locationsFlow` will ends\n
scope.launch {\nhandleLiveLocation(\nit.chat.id,\nlocationsFlow,\nsentMessageFlow = FlowCollector { currentMessageState.emit(it) }\n)\n}\n// this code will be called right after launch will be completed\n
See our example to get more detailed sample
For the text creating there are several tools. The most simple one is to concatenate several text sources to make list of text sources as a result:
val sources = \"Regular start of text \" + bold(\"with bold part\") + italic(\"and italic ending\")\n
But there is a little bit more useful way: entities builder:
val items = (0 until 10).map { it.toString() }\nbuildEntities(\" \") {// optional \" \" auto separator which will be pasted between text sources\n+\"It is regular start too\" + bold(\"it is bold as well\")\nitems.forEachIndexed { i, item ->\nif (i % 2) {\nitalic(item)\n} else {\nstrikethrough(item)\n}\n}\n}\n
In the code above we are creating an items list just for demonstrating that inside of buildEntities body we may use any operations for cunstructing our result list of TextSources. As a result, will be created the list which will looks like in telegram as \u201cIt is regular start too it is bold as well 0 ~~1~~ 2 ~~3~~ 4 ~~5~~ 6 ~~7~~ 8 ~~9~~\u201d.
TextSource
BehaviourBuilder
You may create subcontext with BehaviourBuilder.createSubContextAndDoWithUpdatesFilter and pass there updatesUpstreamFlow parameter with any operations over parent behaviour builder:
BehaviourBuilder.
createSubContextAndDoWithUpdatesFilter
updatesUpstreamFlow
buildBehaviourWithLongPolling {\ncreateSubContextAndDoWithUpdatesFilter(\nupdatesUpstreamFlow = filter { /* some condition */ },\nstopOnCompletion = false // disable stopping of sub context after setup\n) {\nonCommand() //...\n}\n}\n
updatesUpstreamFlow = filter { it.sourceChat() ?.id == requiredChatId || it.sourceUser() ?.id == requiredUserId }\n
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.
The first thing you need to know is that there are two types of keyboards available in the Telegram Bot API: reply and inline keyboards.
Resize option
In the screenshots above (and in the most others) you may see usage of reply keyboards without resize_keyboard. In case you will use resize_keyboard = true the keyboard will be smaller.
resize_keyboard
resize_keyboard = true
Note the differences in the way these keyboards are shown to a user.
A reply keyboard is shown under the message input field. It replaces the device\u2019s native input method on a mobile device.
An inline keyboard is shown as a part of the message in the chat.
When a user clicks on a simple reply keyboard button, its text is just sent in the chat.
When a user clicks on a simple inline keyboard button, nothing is sent to the chat. Instead, a callback query (a fancy way to say \u201ca request\u201d) is sent directly to the bot and the button is highlighted. It will stay highlighted until the bot acks the callback.
It\u2019s a common mistake to forget to handle callback queries
It leads to the buttons being highlighted for long periods of time, which leads to a bad user experience. Don\u2019t forget to handle these callbacks!
As new messages arrive, a reply keyboard will stay there, while the inline keyboard will stick to the message and move with it.
Ups\u2026 The reply keyboard is now far away from the message it was sent with.
Actually, they are two different unrelated entities now: the original message and the reply keyboard. A reply keyboard persists until you explicitly remove it or replace it with a different one.
It\u2019s a common mistake to forget to remove or replace reply keyboards
It leads to the keyboards being shown forever. Don\u2019t forget to remove reply keyboards when you don\u2019t need them anymore!
You also may use option one_time_keyboard and the keyboard will be automatically removed after user interaction
one_time_keyboard
An inline keyboard could also be removed or changed by editing the original message it was attached to.
Keyboards are not limited to text only. They could be used to ask users for different things, like payments, locations, phone numbers, etc. They could be used to open arbitrary URLs or web apps. Telegram clients process these buttons and interact with the users in the appropriate ways.
For the full list of options, see the official documentation on reply and inline keyboards.
Now, that you know the basics, let\u2019s see how to use the library.
In Telegram Bot API keyboards are sent to the user as a part of an interaction via the reply_markup parameter. More specifically, this parameter is available:
reply_markup
sendXXX
sendMessage
sendPhoto
sendSticker
copyMessage
editMessageXXX
editMessageText
editMessageCaption
editMessageReplyMarkup
stopXXX
stopMessageLiveLocation
Tip
editMessageReplyMarkup is specifically designed to edit a message\u2019s inline keyboard.
Sending inline keyboards is also supported in inline mode through the reply_markup parameter of the InlineQueryResult type and its inheritors. However, this inline mode is unrelated to the inline keyboards.
InlineQueryResult
The reply_markup parameter accepts four different types. Two of them \u2014 ReplyKeyboardMarkup and InlineKeyboardMarkup \u2014 correspond to the reply and inline keyboards respectively. The ReplyKeyboardRemove type is used to remove reply keyboards, but it\u2019s not a keyboard itself. The last one, ForceReply, is used to force users to reply to the bot. It is not a keyboard either, but yet another dirty hack employed by the Telegram Bot API.
ReplyKeyboardMarkup
InlineKeyboardMarkup
ReplyKeyboardRemove
ForceReply
Now, in the library, the WithReplyMarkup is a marker interface for all the interactions which could have a replyMarkup (represents reply_markup) parameter. It is extended by the ReplyingMarkupSendMessageRequest, and then, finally, by classes like SendTextMessage. This, basically, corresponds to the Telegram Bot API.
WithReplyMarkup
replyMarkup
ReplyingMarkupSendMessageRequest
SendTextMessage
Note
You may see all the inheritors of WithReplyMarkup interfaces in the corresponding KDoc
The other way to send a keyboard is through the replyMarkup parameter of the numerous extension methods, like sendMessage. Those are just convenient wrappers around general interaction classes, like the aforementioned SendTextMessage.
As we already know, keyboards consist of buttons. Button classes reside in the dev.inmo.tgbotapi.types.buttons package.
dev.inmo.tgbotapi.types.buttons
The base class for the reply keyboard buttons is the KeyboardButton. The base class for the inline keyboard buttons is the InlineKeyboardButton.
KeyboardButton
InlineKeyboardButton
See their inheritors for the full list of the available buttons. The names are pretty self-explanatory and correspond to the Telegram Bot API.
For example, to send a simple reply keyboard button, use the SimpleKeyboardButton class. To request a contact from the user through the reply, use the RequestContactKeyboardButton class. To attach a URL button to the message, use the URLInlineKeyboardButton. And to attach a callback button, use the CallbackDataInlineKeyboardButton.
SimpleKeyboardButton
RequestContactKeyboardButton
URLInlineKeyboardButton
CallbackDataInlineKeyboardButton
You get the idea.
So, to send a reply keyboard use the following code:
bot.sendMessage(\nchatId = chat,\ntext = \"What is the best Kotlin Telegram Bot API library?\",\nreplyMarkup = ReplyKeyboardMarkup(\nkeyboard = listOf(\nlistOf(\nSimpleKeyboardButton(\"ktgbotapi\"),\n),\n)\n)\n)\n
And here is how you send a basic inline keyboard:
bot.sendMessage(\nchatId = chat,\ntext = \"ktgbotapi is the best Kotlin Telegram Bot API library\",\nreplyMarkup = InlineKeyboardMarkup(\nkeyboard = listOf(\nlistOf(\nCallbackDataInlineKeyboardButton(\"I know\", \"know\"),\nURLInlineKeyboardButton(\"Learn more\", \"https://github.com/InsanusMokrassar/ktgbotapi\")\n),\n)\n),\n)\n
When we\u2019re done with this simple quiz, we can remove the keyboard with the following code:
bot.sendMessage(\nchatId = chat,\ntext = \"You're goddamn right!\",\nreplyMarkup = ReplyKeyboardRemove()\n)\n
Don\u2019t forget to remove the reply keyboards!
Buttons in keyboards are arranged in matrices, i.e. two-dimensional arrays, or, to say in layperson\u2019s terms, rows and columns. In contrast to the matrices you\u2019ve learned in school, keyboards are not always necessarily square. Try it:
bot.sendMessage(\nchatId = chat,\ntext = \"In contrast to the matrices you've learned in school, keyboards are not always necessary square.\",\nreplyMarkup = InlineKeyboardMarkup(\nkeyboard = listOf(\nlistOf(\nCallbackDataInlineKeyboardButton(\"1\", \"1\"),\nCallbackDataInlineKeyboardButton(\"2\", \"2\"),\nCallbackDataInlineKeyboardButton(\"3\", \"3\"),\n),\nlistOf(\nCallbackDataInlineKeyboardButton(\"4\", \"4\"),\nCallbackDataInlineKeyboardButton(\"5\", \"5\"),\n),\nlistOf(\nCallbackDataInlineKeyboardButton(\"6\", \"6\"),\n)\n)\n)\n)\n
This way of building matrices is not very convenient, so the library provides a few eloquent DSLs to simplify that.
First, there are matrix and row, so the keyboard above can be built like this:
matrix
row
bot.sendMessage(\nchatId = chat,\ntext = \"DSLs are sweet!\",\nreplyMarkup = InlineKeyboardMarkup(\nkeyboard = matrix {\nrow {\n+CallbackDataInlineKeyboardButton(\"1\", \"1\")\n+CallbackDataInlineKeyboardButton(\"2\", \"2\")\n+CallbackDataInlineKeyboardButton(\"3\", \"3\")\n}\nrow(\nCallbackDataInlineKeyboardButton(\"4\", \"4\"),\nCallbackDataInlineKeyboardButton(\"5\", \"5\"),\n)\nrow {\n+CallbackDataInlineKeyboardButton(\"6\", \"6\")\n}\n},\n)\n)\n
Those plus signs are mandatory.
There are two different row functions here. Can you spot the difference?
A single-row matrix can be built with a flatMatrix:
flatMatrix
flatMatrix {\n+CallbackDataInlineKeyboardButton(\"1\", \"1\")\n+CallbackDataInlineKeyboardButton(\"2\", \"2\")\n+CallbackDataInlineKeyboardButton(\"3\", \"3\")\n+CallbackDataInlineKeyboardButton(\"4\", \"4\")\n+CallbackDataInlineKeyboardButton(\"5\", \"5\")\n}\n
But the most convenient way to build a simple keyboard is to use the constructor-like methods: InlineKeyboardMarkup and ReplyKeyboardMarkup. Note, that they are named just like the corresponding constructor, but take a vararg of buttons. They create flat matrices, i.e. single rows.
Finally, there are inlineKeyboard and replyKeyboard
inlineKeyboard
replyKeyboard
DSL methods above rely on Kotlin\u2019s feature of receivers and extensions. So, the magic is done by MatrixBuilder and RowBuilder. That\u2019s why you must use the plus sign to add buttons to the matrix: it\u2019s just an overloaded operator call, another cool Kotlin feature widely used to create sweet DSLs.
MatrixBuilder
RowBuilder
Another bonus of using these DSLs is button builders, like payButton, dataButton, and urlButton:
payButton
dataButton
urlButton
bot.sendMessage(\nchatId = chat,\ntext = \"All in one!\",\nreplyMarkup = InlineKeyboardMarkup(\nkeyboard = matrix {\nrow {\npayButton(\"Send money\")\ndataButton(\"Ok\", \"ok\")\nurlButton(\"Google\", \"https://google.com\")\n}\n},\n)\n)\n
Reply keyboard builders provide similar extensions, e.g. requestLocationButton.
requestLocationButton
So, choose the style you like \u2014 from plain Kotlin lists to sweet DSLs \u2014 and use it!
Working with keyboards is not something special in Telegram Bot API. As you have already seen, keyboards are just message parameters. Similarly, keyboard interactions are represented by regular Updates. I.e. when a user interacts with a keyboard, the bot receives an update.
On the other hand, the library is heavily typed, so the actual type of update you would receive varies.
As it was said, reply keyboards cause Telegram clients to send regular messages back to the bot. Peruse this example:
bot.buildBehaviourWithLongPolling {\nbot.sendMessage(\nchatId = chat,\ntext = \"\ud83d\udc6e Turn in your accomplices or be prepared for a lengthy \ud83c\udf46 incarceration \u26d3 \ud83d\udc4a \u203c\",\nreplyMarkup = 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\",\nKeyboardButtonRequestUser.Common(RequestId.random())\n)\n+RequestChatKeyboardButton(\n\"Rat out \ud83d\udc00 a group of friends \ud83d\udc65\",\nKeyboardButtonRequestChat.Group(RequestId.random())\n)\n}\n)\nonText { message: CommonMessage<TextContent> ->\nassert(message.text == \"I ain't no rat! \ud83d\udeab\ud83d\udc00\ud83e\udd10\ud83d\ude45\")\nbot.reply(\nto = message,\ntext = \"Good, you're going to jail alone! \u26d3\ud83e\uddd1\u26d3\",\nreplyMarkup = ReplyKeyboardRemove()\n)\n}\nonUserShared { message: PrivateEventMessage<UserShared> ->\nbot.reply(\nto = message,\ntext = \"Haha, you and you friend are both going to jail! \u26d3\ud83d\udc6c\u26d3\",\nreplyMarkup = ReplyKeyboardRemove()\n)\n}\nonChatShared { message: PrivateEventMessage<ChatShared> ->\nbot.reply(\nto = message,\ntext = \"Haha, now you're all going to jail! \u26d3\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66\u26d3\",\nreplyMarkup = ReplyKeyboardRemove()\n)\n}\n}.join()\n
Read more about buildBehaviourWithLongPolling here
buildBehaviourWithLongPolling
I hope you get the idea: the bot acts like a cop and asks the user to rat out his friends via a reply keyboard (it\u2019s an imaginary situation, of course). The user may refuse to cooperate, rat out a single friend or the whole imaginary group. The bot receives the user\u2019s choices as regular updates, the code above has explicit types (generally optional in Kotlin) and an assert to demonstrate this.
And here is how it works (the user selects the options in the order):
Note how you handle reply keyboards: you process regular messages. For instance, a simple text button sends a regular text message indistinguishable from a case when a user simply types the same text manually.
And don\u2019t be a rat in real life: remove the keyboards with the ReplyKeyboardRemove after you\u2019ve received the input! Otherwise, a keyboard will stay there indefinitely.
Finally, to master the keyboards, you need to know how to handle the inline ones.
Again, let\u2019s explore the example. Imagine you\u2019re making a quiz where users are given a question and a set of answers. Additionally, users are given a link to the wiki page to help with the question and a Google button.
The quiz could be implemented this way:
// A simple data class to represent a question\nval question = Question(\nimage = \"https://upload.wikimedia.org/wikipedia/commons/a/a5/Tsunami_by_hokusai_19th_century.jpg\",\nquestion = \"Who painted this?\",\nanswers = listOf(\nAnswer(\"Hokusai\", correct = true),\nAnswer(\"Sukenobu\"),\nAnswer(\"Ch\u014dshun\"),\nAnswer(\"Kiyonobu I\"),\n),\nwiki = \"https://en.wikipedia.org/wiki/Ukiyo-e\",\n)\nbot.buildBehaviourWithLongPolling {\nbot.sendPhoto(\nchatId = chat,\nfileId = InputFile.fromUrl(question.image),\ntext = question.question,\nreplyMarkup = inlineKeyboard {\n// First row: answers\nrow {\nfor (answer in question.answers.shuffled()) {\ndataButton(\ntext = answer.answer,\ndata = \"${answer.answer}:${answer.correct}\",\n)\n}\n}\n// Second row: help buttons\nrow {\nurlButton(\"Wiki \ud83d\udc81\", question.wiki)\nwebAppButton(\"Google \ud83d\udd0d\", \"https://google.com\")\n}\n}\n)\nonDataCallbackQuery { callback: DataCallbackQuery ->\nval (answer, correct) = callback.data.split(\":\")\nif (correct.toBoolean()) {\nbot.answerCallbackQuery(\ncallback,\ntext = \"$answer is a \u2705 correct answer!\",\nshowAlert = true\n)\n} else {\nbot.answerCallbackQuery(\ncallback,\ntext = \"\u274c Try again, $answer is not a correct answer\u2026\",\nshowAlert = true\n)\n}\n}\n}.join()\n
A few important things to note here.
First, the data buttons (they have the CallbackDataInlineKeyboardButton type, but in the code we used a neat DSL) must have unique data. If the data is not unique, Telegram clients will highlight all the buttons with the same data when a user clicks on one of them. Guess how I know that? Well, it\u2019s not in the docs, so trial and error is the only way to learn it (and many other things about the Telegram Bot API).
data
Second, the way you handle inline keyboards is different from the way you handle reply keyboards. Bot API will send updates with a callback_query field populated. This field, of a CallbackQuery type, represents incoming callbacks from callback buttons in inline keyboards. The library turns them into multiple callback types, like the DataCallbackQuery we used in the example. Finally, to handle these callbacks you could use onDataCallbackQuery. Alternatively, if you\u2019re not using any DSLs, you have to handle the CallbackQueryUpdate update type.
callback_query
CallbackQuery
DataCallbackQuery
onDataCallbackQuery
CallbackQueryUpdate
Third, the buttons got highlighted when a user clicks on them. When you\u2019re done with the callback, you need to answer it, by using the answerCallbackQuery function. Otherwise, the button will remain highlighted. Telegram clients will eventually remove the highlight, but it\u2019s still frustrating.
answerCallbackQuery
Finally, you could choose between two styles of acknowledgment: a simple toast-like message or a modal alert. The showAlert flag controls this behavior.
showAlert
And here is the demo of the quiz:
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.
There are several places you need to visit for starting work with any Telegram Bot framework on any language:
Anyway, the most important link is How do I create a bot? inside of Telegram Bot API
Examples info
A lot of examples with using of Telegram Bot API you can find in this github repository
The most simple bot will just print information about itself. All source code you can find in this repository. Our interest here will be concentrated on the next example part:
suspend fun main(vararg args: String) {\nval botToken = args.first()\nval bot = telegramBot(botToken)\nprintln(bot.getMe())\n}\n
So, let\u2019s get understanding, about what is going on:
suspend fun main(vararg args: String)
suspend
suspend fun main
fun main() = runBlocking {}
val botToken = args.first()
val bot = telegramBot(botToken)
bot
println(bot.getMe())
As a result, we will see in the command line something like
ExtendedBot(id=ChatId(chatId=123456789), username=Username(username=@first_test_ee17e8_bot), firstName=Your bot name, lastName=, canJoinGroups=false, canReadAllGroupMessages=false, supportsInlineQueries=false)\n
There are three projects:
TelegramBotAPI Core
TelegramBotAPI API Extensions
TelegramBotAPI
TelegramBotAPI Utils Extensions
Also, there is an aggregator-version tgbotapi, which will automatically include all projects above. It is most recommended version due to the fact that it is including all necessary tools around TelegramBotAPI Core, but it is optionally due to the possible restrictions on the result methods count (for android) or bundle size
tgbotapi
Examples
You can find full examples info in this repository. In this repository there full codes which are working in normal situation. Currently, there is only one exception when these examples could work incorrectly: you are living in the location where Telegram Bot API is unavailable. For solving this problem you can read Proxy setup part
To use this library, you will need to include Maven Central repository in your project
Maven Central
<repository>\n<id>central</id>\n<name>mavenCentral</name>\n<url>https://repo1.maven.org/maven2</url>\n</repository>\n
Besides, there is developer versions repo. To use it in your project, add the repo in repositories section:
repositories
maven {\nurl \"https://git.inmo.dev/api/packages/InsanusMokrassar/maven\"\n}\n
<repository>\n<id>dev.inmo</id>\n<name>InmoDev</name>\n<url>https://git.inmo.dev/api/packages/InsanusMokrassar/maven</url>\n</repository>\n
As tgbotapi_version variable in next snippets will be used variable with next last published version:
implementation \"dev.inmo:tgbotapi:$tgbotapi_version\"\n
<dependency>\n<groupId>dev.inmo</groupId>\n<artifactId>tgbotapi</artifactId>\n<version>${tgbotapi_version}</version>\n</dependency>\n
implementation \"dev.inmo:tgbotapi.core:$tgbotapi_version\"\n
<dependency>\n<groupId>dev.inmo</groupId>\n<artifactId>tgbotapi.core</artifactId>\n<version>${tgbotapi_version}</version>\n</dependency>\n
implementation \"dev.inmo:tgbotapi.api:$tgbotapi_version\"\n
<dependency>\n<groupId>dev.inmo</groupId>\n<artifactId>tgbotapi.api</artifactId>\n<version>${tgbotapi_version}</version>\n</dependency>\n
implementation \"dev.inmo:tgbotapi.utils:$tgbotapi_version\"\n
<dependency>\n<groupId>dev.inmo</groupId>\n<artifactId>tgbotapi.utils</artifactId>\n<version>${tgbotapi_version}</version>\n</dependency>\n
In some locations Telegram Bots API urls will be unavailable. In this case all examples will just throw exception like:
Exception in thread \"main\" java.net.ConnectException: Connection refused\n at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)\nat sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)\nat io.ktor.network.sockets.SocketImpl.connect$ktor_network(SocketImpl.kt:36)\nat io.ktor.network.sockets.SocketImpl$connect$1.invokeSuspend(SocketImpl.kt)\nat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)\nat kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)\nat kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)\nat kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:738)\nat kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)\nat kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)\nProcess finished with exit code 1\n
There are several ways to solve this problem:
First of all, you will need to use one more library:
build.gradle:
implementation \"io.ktor:ktor-client-okhttp:2.0.1\"\n
Dependency note
In the snippet above was used version 2.0.1 which is actual for TelegramBotAPI at the moment of filling this documentation (May 22 2022, TelegramBotAPI version 2.0.0) and you can update version of this dependency in case if it is outdated.
2.0.1
May 22 2022
2.0.0
For configuring proxy for your bot inside your program, you can use next snippet:
val botToken = \"HERE MUST BE YOUR TOKEN\"\nval bot = telegramBot(botToken) {\nktorClientEngineFactory = OkHttp\nproxy = ProxyBuilder.socks(\"127.0.0.1\", 1080)\n}\n
Explanation line by line:
val botToken = \"HERE MUST BE YOUR TOKEN\"
botToken
val bot = telegramBot(botToken) {
ktorClientEngineFactory = OkHttp
OkHttp
Ktor
proxy = ProxyBuilder.socks(\"127.0.0.1\", 1080)
shadowsocks
API extensions is a module which you may include in your project in addition to core part. In most cases this module will allow just use syntax like bot.getUpdates() instead of bot.execute(GetUpdates()), but there are several other things you will achieve with that syntax.
bot.getUpdates()
bot.execute(GetUpdates())
This functionality allow you to build bot in more unified and comfortable way than standard creating with telegramBot function
telegramBot
buildBot(\n\"TOKEN\"\n) {\nproxy = ProxyBuilder.socks(host = \"127.0.0.1\", port = 4001) // just an example, more info on https://ktor.io/docs/proxy.html\nktorClientConfig = {\n// configuring of ktor client\n}\nktorClientEngineFactory = {\n// configuring of ktor client engine \n}\n}\n
In standard library requests there are no way to download some file retrieved in updates or after requests. You may use syntax like bot.downloadFile(file) where file is TelegramMediaFile from telegram, FileId or even PathedFile from GetFile request (sources).
bot.downloadFile(file)
file
TelegramMediaFile
FileId
PathedFile
By default, you should handle updates of Live location by your code. But with extension bot#startLiveLocation you may provide all necessary startup parameters and handle updates with just calling updateLocation for retrieved LiveLocationProvider.
updateLocation
There are several things you may read next:
Behaviour builder with FSM is based on the MicroUtils FSM. There are several important things in FSM:
State
StateHandler
StatesMachine have two methods:
StatesMachine
start
startChain
The most based way to create StatesMachine and register StateHandlers looks like in the next snippet:
buildFSM<TrafficLightState> {\nstrictlyOn<SomeState> {\n// state handling\n}\n}.start(CoroutineScope(...)).join()\n
Full example
You may find full example of FSM usage in the tests of FSM in MicroUtils
So, you must do next steps before you will launch your bot with FSM:
There are several extensions for TelegramBot to create your bot with FSM:
TelegramBot
All of them will take as an callback some object with type CustomBehaviourContextReceiver and will looks like in the next snippet:
telegramBotWithBehaviourAndFSMAndStartLongPolling<YourStateType>(\"BOT_TOKEN\") {\n// here you may use any operations from BehaviourBuilder\n// here you may use any operations from BehaviourContextWithFSMBuilder like strictlyOn and others\n}\n
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.
There are several things you should know for better understanding of behaviour builder:
on*
BehaviourContext
wait*
As was said above, there is buildBehaviour function which allow you set up your bot logic. Let\u2019s see an example:
val bot = telegramBot(\"TOKEN\")\nbot.buildBehaviour {\nonCommand(\"start\") { // creating of trigger\nval message = it\nval content = message.content\nreply(message, \"Ok, send me one photo\") // send text message with replying on incoming message\nval photoContent = waitPhoto().first() // waitPhoto will return List, so, get first element\nval photo = downloadFile(photoContent) // ByteArray of photo\n// some logic with saving of photos\n}\n}\n
In most cases there are opportunity to filter some of messages before starting of main logic. Let\u2019s look at this using the example above:
val bot = telegramBot(\"TOKEN\")\nbot.buildBehaviour {\nonCommand(\n\"start\",\ninitialFilter = {\nit.content.textSources.size == 1 // make sure that user has sent /start without any additions\n}\n) {\n// ...\n}\n}\n
val bot = telegramBot(\"TOKEN\")\nbot.buildBehaviour {\nonCommand(\n\"start\",\nrequireOnlyCommandInMessage = true // it is default, but you can overwrite it with `requireOnlyCommandInMessage = false`\n) {\n// ...\n}\n}\n
Unfortunatelly, exceptions handling in this library is a bit difficult in some places, but that have at least two reasons: flexibility and usability.
In case you know, where exceptions are happening, you may use several tools for exceptions catching:
If you prefer to receive Result objects instead of some weird callbacks, you may use the next syntax:
Result
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\nit.printStackTrace()\n}.getOrThrow() // will return value or throw exception\n
Also there is more simple (in some cases) way to handle exceptions with callbacks:
safely(\n{\n// handle error\nit.printStackTrace()\nnull // return value\n}\n) {\n// do something\n}\n
There are two types of handling:
safely(\n{\nit.printStackTrace()\n\"error\"\n}\n) {\nerror(\"Hi :)\") // emulate exception throwing\n\"ok\"\n} // result will be with type String\n
safely
safelyWithouExceptions {\n// do something\n} // will returns nullable result type\n
The most simple way to configure exceptions handling is to change CoroutineContext when you are creating your CoroutineScope for bot processing:
CoroutineContext
CoroutineScope
val bot = telegramBot(\"TOKEN\")\nbot.buildBehaviour (\nscope = scope,\ndefaultExceptionsHandler = {\nit.printStackTrace()\n}\n) {\n// ...\n}\n
val bot = telegramBotWithBehaviour (\n\"TOKEN\",\nscope = scope,\ndefaultExceptionsHandler = {\nit.printStackTrace()\n}\n) {\n// ...\n}\n
Here we have used ContextSafelyExceptionHandler class. It will pass default handling of exceptions and will call the block in most cases when something inside of your bot logic has thrown exception.
ContextSafelyExceptionHandler
According to the documentation there are several ways to work with files:
typealias
There are several cases you may need in your app to work with files:
The most simple way to send some file is to get file id and send it. You may get file id from any message with media. For example, if you have received some Message, you may use asCommonMessage conversation to be able to get its content and then convert it to some content with media. Full code here:
content
val message: Message;\nval fileId = message.asCommonMessage() ?.withContent<MediaContent>() ?.content ?.media ?.fileId;\n
WAT? O.o
In the code above we get some message, safely converted it to CommonMessage with asCommonMessage, then safely took its content via withContent<MediaContent>() ?.content and then just get its media file id.
CommonMessage
asCommonMessage
withContent<MediaContent>() ?.content
There are three ways to download files:
ByteArray
ByteReadChannelAllocator
[JVM Only]
API
val bot: TelegramBot;\nval fileId: FileId;\nval outputFile: File;\nbot.downloadFile(fileId, outputFile)\n
See downloadFile extension docs in the JVM tab to get more available options
There is also way with saving of data into temporal file. That will allow you to do with data whatever you want without high requirements to memory or network connection:
val bot: TelegramBot;\nval fileId: FileId;\nval tempFile: File = bot.downloadFileToTemp(fileId)\n
See downloadFileToTemp extension docs to get more available options
val bot: TelegramBot;\nval fileId: FileId;\nval bytes: ByteReadChannelAllocator = bot.downloadFileStream(fileId)\n
See downloadFileStream extension docs to get more available options
val bot: TelegramBot;\nval fileId: FileId;\nval bytes: ByteReadChannelAllocator = bot.downloadFileStreamAllocator(fileId)\n
See downloadFileStreamAllocator extension docs to get more available options
val bot: TelegramBot;\nval fileId: FileId;\nval bytes: ByteArray = bot.downloadFile(fileId)\n
See downloadFile extension docs to get more available options
how does it work?
You may download file with streams or with downloading into the memory first. On low level you should do several things. They are presented in next snippet:
val bot: TelegramBot;\nval fileId: FileId;\nval pathedFile: PathedFile = bot.execute(GetFile(fileId))\nval downloadedBytes: ByteArray = bot.execute(DownloadFile(pathedFile.filePath))\n
In the snippet above we are getting file PathedFile by its FileId and use it to download file bytes into memory using DownloadFile request.
DownloadFile
You may use almost the same way but with byte read channel allocator:
val bot: TelegramBot;\nval fileId: FileId;\nval pathedFile: PathedFile = bot.execute(GetFile(fileId))\nval channelAllocator: ByteReadChannelAllocator = bot.execute(DownloadFileStream(pathedFile.filePath))\nval byteReadChannel: ByteReadChannel = channelAllocator()\n
And then you may look into ByteReadChannel docs to get more info about what you can do with that.
Several useful links
Of course, in most cases you must be sure that file have correct type.
It is the most simple way to send any media in Telegram, but this way have several restrictions:
JS Restrictions
Sending via file is accessible from all supported platforms, but there is small note about JS - due to restrictions of work with streams and stream-like data (JS have no native support of files streaming) on this platform all the files will be loaded inside of RAM before the sending to the telegram services.
Sending via file is available throw the MultipartFile. There are several wayt to get it:
MultipartFile(\"filename.jpg\") { /* here Input allocation */ }
ByteReadChannel
File
In most cases, sending via files looks like in the next snippet:
val file: File;\nbot.sendDocument(chatId, file.asMultipartFile())\n
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.
There are several important things in context of this library:
So, in most cases all your request calls with simplified api of this library (like bot.getMe()) will looks like bot.execute(GetMe). Result of these calls is defined in type of any request (for example, for GetMe request the result type is ExtendedBot). As a result, you can avoid any extension api (like special API extensions) and use low level request with full controlling of the whole logic flow.
bot.getMe()
bot.execute(GetMe)
As was written above, it will require some request:
val updates = bot.execute(GetUpdates())\n
Result type of GetUpdates request is Update. You may find inheritors of this interface in Update kdocs.
As was said above, you may look into our API extensions in case you wish to use more high-level functions instead of bot.execute(SomeRequest()). Besides, it will be very useful to know more about updates retrieving.
bot.execute(SomeRequest())
As you know, Telegram have the feature named Media Groups. Media groups have several differences with the common messages:
Row updates
In tgbotapi there is no any additional handling of media groups by default and in case you will use simple bot.getUpdates, you will get the list of row updates and media groups will be included in this list as separated messages with MediaGroupPartContent. In that case you may use convertWithMediaGroupUpdates to be able to work with media groups as will be described below
In case you are using standard long polling (one of alternatives is telegramBotWithBehaviourAndLongPolling) or webhooks updates will be converted uner the hood and as a result, you will take media groups as a content in one message:
telegramBotWithBehaviourAndLongPolling(\n\"token\"\n) {\nonVisualGallery { // it: CommonMessage<MediaGroupContent<VisualMediaGroupPartContent>>\nit.content // MediaGroupContent<VisualMediaGroupPartContent>\nit.content.group // List<MediaGroupCollectionContent.PartWrapper<VisualMediaGroupPartContent>>\nit.content.group.forEach { // it: MediaGroupCollectionContent.PartWrapper<VisualMediaGroupPartContent>\nit.messageId // source message id for current media group part\nit.sourceMessage // source message for current media group part\nit.content // VisualMediaGroupPartContent\nprintln(it.content) // will print current content part info\n}\n}\n}\n
KDocs:
In two words, in difference with row Telegram Bot API, you will take media groups in one message instead of messages list.
One of the most important topics in context of tgbotapi is types conversations. This library is very strong-typed and a lot of things are based on types hierarchy. Lets look into the hierarchy of classes for the Message in 0.35.8:
As you may see, it is a little bit complex and require several tools for types conversation.
as conversations will return new type in case if it is possible. For example, when you got Message, you may use asContentMessage conversation to get message with content:
as
Message
asContentMessage
val message: Message;\nprintln(message.asContentMessage() ?.content)\n
This code will print null in case when message is not ContentMessage, and content when is.
message
ContentMessage
require works like as, but instead of returning nullable type, it will always return object with required type OR throw ClassCastException:
require
ClassCastException
val message: Message;\nprintln(message.requireContentMessage().content)\n
This code will throw exception when message is not ContentMessage and print content when is.
when extensions will call passed block when type is correct. For example:
when
val message: Message;\nmessage.whenContentMessage {\nprintln(it.content)\n}\n
Code placed above will print content when message is ContentMessage and do nothing when not
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.
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:
UpdatesFilter
flowsUpdatesFilter
Let\u2019s look how it works with the factory above:
// Step 1 - create filter\nval filter = flowsUpdatesFilter {\n// Step 2 - set up handling. In this case we will print any message from group or user in console\nmessageFlow.onEach {\nprintln(it)\n}.launchIn(someCoroutineScope)\n}\n// Step 3 - passing updates to filter\nbot.getUpdates().forEach {\nfilter.asUpdatesReceiver(it)\n}\n
Some example with long polling has been described above. But it is more useful to use some factories for it. In this page we will look for simple variant with TelegramBot#longPolling. So, with this function, your handling of updates will looks like:
val bot = telegramBot(\"TOKEN\")\nbot.longPolling {\nmessageFlow.onEach {\nprintln(it)\n}.launchIn(someCoroutineScope)\n}.join()\n
This example looks like the example above with three steps, but there are several important things here:
.join()
longPolling
Job
cancel
job.cancel()
join
What is next?
As a result you can start listen updates and react on it. Next recommended articles:
Preview reading
It is recommended to visit our pages about UpdatesFilters and Webhooks to have more clear understanding about what is happening in this examples page
Heroku is a popular place for bots hosting. In common case you will need to configure webhooks for your server to include getting updates without problems. There are several things related to heroku you should know:
https://<app name>.herokuapp.com/
System.getenv(\"PORT\").toInt()
Sat Aug 15 5:04:21 +00 2020
Server configuration alternatives
Here will be presented variants of configuration of webhooks and starting server. You always able to set webhook manualy, create your own ktor server and include webhooks handling in it or create and start server with only webhooks handling. More info you can get on page Webhooks
suspend fun main {\n// This subroute will be used as random webhook subroute to improve security according to the recommendations of Telegram\nval subroute = uuid4().toString()\n// Input/Output coroutines scope more info here: https://kotlinlang.org/docs/coroutines-guide.html\nval scope = CoroutineScope(Dispatchers.IO)\n// Here will be automatically created bot and available inside of lambda where you will setup your bot behaviour\ntelegramBotWithBehaviour(\n// Pass TOKEN inside of your application environment variables\nSystem.getenv(\"TOKEN\"),\nscope = scope\n) {\n// Set up webhooks and start to listen them\nsetWebhookInfoAndStartListenWebhooks(\n// Automatic env which will be passed by heroku to the app\nSystem.getenv(\"PORT\").toInt(),\n// Server engine. More info here: https://ktor.io/docs/engines.html\nTomcat,\n// Pass URL environment variable via settings of application. It must looks like https://<app name>.herokuapp.com\nSetWebhook(\"${System.getenv(\"URL\").removeSuffix(\"/\")}/$subroute\"),\n// Just callback which will be called when exceptions will happen inside of webhooks\n{\nit.printStackTrace()\n},\n// Set up listen requests from outside\n\"0.0.0.0\",\n// Set up subroute to listen webhooks to\nsubroute,\n// BehaviourContext is the CoroutineScope and it is recommended to pass it inside of webhooks server\nscope = this,\n// BehaviourContext is the FlowsUpdatesFilter and it is recommended to pass its asUpdateReceiver as a block to retrieve all the updates\nblock = asUpdateReceiver\n)\n// Test reaction on each command with reply and text `Got it`\nonUnhandledCommand {\nreply(it, \"Got it\")\n}\n}\n// Just potentially infinite await of bot completion\nscope.coroutineContext.job.join()\n}\n
// 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)\nval filter = flowsUpdatesFilter {\nmessageFlow.onEach {\nprintln(it) // will be printed \n}.launchIn(scope)\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\nval server = bot.setWebhookInfoAndStartListenWebhooks(\n// Automatic env which will be passed by heroku to the app\nSystem.getenv(\"PORT\").toInt(),\n// Server engine. More info here: https://ktor.io/docs/engines.html\nTomcat,\n// Pass URL environment variable via settings of application. It must looks like https://<app name>.herokuapp.com\nSetWebhook(\"${System.getenv(\"URL\").removeSuffix(\"/\")}/$subroute\"),\n// Just callback which will be called when exceptions will happen inside of webhooks\n{\nit.printStackTrace()\n},\n// Set up listen requests from outside\n\"0.0.0.0\",\n// Set up subroute to listen webhooks to\nsubroute,\nscope = scope,\nblock = filter.asUpdateReceiver\n)\nserver.environment.connectors.forEach {\nprintln(it)\n}\nserver.start(false)\n
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.
There are a lot of ways to include work with long polling:
RequestsExecutor#longPollingFlow
RequestsExecutor#startGettingOfUpdatesByLongPolling
RequestsExecutor#longPolling
startGettingOfUpdatesByLongPolling
RequestsExecutor#createAccumulatedUpdatesRetrieverFlow
longPollingFlow
RequestsExecutor#retrieveAccumulatedUpdates
createAccumulatedUpdatesRetrieverFlow
RequestsExecutor#flushAccumulatedUpdates
retrieveAccumulatedUpdates
GetUpdates
RequestsExecutor#getUpdates
longPolling is a simple way to start getting updates and work with bot:
val bot = telegramBot(token)\nbot.longPolling(\ntextMessages().subscribe(scope) { // here \"scope\" is a CoroutineScope\nprintln(it) // will be printed each update from chats with messages\n}\n)\n
The main aim of startGettingOfUpdatesByLongPolling extension was to provide more simple way to get updates in automatic mode:
val bot = telegramBot(token)\nbot.startGettingOfUpdatesByLongPolling(\n{\nprintln(it) // will be printed each update from chats with messages\n}\n)\n
The other way is to use the most basic startGettingOfUpdatesByLongPolling extension:
val bot = telegramBot(token)\nbot.startGettingOfUpdatesByLongPolling {\nprintln(it) // will be printed each update\n}\n
Due to the fact, that anyway you will get updates in one format (Update objects), some time ago was solved to create one point of updates filters for more usefull way of updates handling
Update
UpdatesFilter currently have two properties:
asUpdateReceiver
allowedUpdates
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).
SimpleUpdatesFilter is a simple variant of filters. It have a lot of UpdateReceiver properties which can be set up on creating of this object. For example, if you wish to get messages from chats (but not from channels), you can use next snippet:
SimpleUpdatesFilter
UpdateReceiver
SimpleUpdatesFilter {\nprintln(it)\n}\n
A little bit more modern way is to use FlowsUpdatesFilter. It is very powerfull API of Kotlin Coroutines Flows, built-in support of additional extensions for FlowsUpdatesFilter and Flow<...> receivers and opportunity to split one filter for as much receivers as you want. Filter creating example:
FlowsUpdatesFilter
Flow<...>
val scope = CoroutineScope(Dispatchers.Default)\nflowsUpdatesFilter {\nmessageFlow.onEach {\nprintln(it)\n}.launchIn(scope)\n}\n
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:
plus
flowsUpdatesFilter {\n(messageFlow + channelPostFlow).onEach {\nprintln(it) // will be printed each message update from channels and chats both\n}.launchIn(scope)\n}\n
aggregateFlows
flowsUpdatesFilter {\naggregateFlows(\nscope,\nmessageFlow,\nchannelPostFlow\n).onEach {\nprintln(it) // will be printed each message update from channels and chats both\n}.launchIn(scope)\n}\n
flowsUpdatesFilter {\nallSentMessagesFlow.onEach {\nprintln(it) // will be printed each message update from channels and chats both\n}.launchIn(scope)\n}\n
FlowsUpdatesFilter have a lot of extensions for messages types filtering:
flowsUpdatesFilter {\ntextMessages(scope).onEach {\nprintln(it) // will be printed each message from channels and chats both with content only `TextContent`\n}.launchIn(scope)\n}\n
The same things were created for media groups:
flowsUpdatesFilter {\nmediaGroupMessages(scope).onEach {\nprintln(it) // will be printed each media group messages list from both channels and chats without filtering of content\n}.launchIn(scope)\nmediaGroupPhotosMessages(scope).onEach {\nprintln(it) // will be printed each media group messages list from both channels and chats with PhotoContent only\n}.launchIn(scope)\nmediaGroupVideosMessages(scope).onEach {\nprintln(it) // will be printed each media group messages list from both channels and chats with VideoContent only\n}.launchIn(scope)\n}\n
Besides, there is an opportunity to avoid separation on media groups and common messages and receive photos and videos content in one flow:
flowsUpdatesFilter {\nsentMessagesWithMediaGroups(scope).onEach {\nprintln(it) // will be printed each message including each separated media group message from both channels and chats without filtering of content\n}.launchIn(scope)\nphotoMessagesWithMediaGroups(scope).onEach {\nprintln(it) // will be printed each message including each separated media group message from both channels and chats with PhotoContent only\n}.launchIn(scope)\nvideoMessagesWithMediaGroups(scope).onEach {\nprintln(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
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:
Route#includeWebhookHandlingInRoute
Route#includeWebhookHandlingInRouteWithFlows
startListenWebhooks
RequestsExecutor#setWebhookInfoAndStartListenWebhooks
setWebhookInfoAndStartListenWebhooks
It is the most common way to set updates webhooks and start listening of them. Example:
val bot = telegramBot(TOKEN)\nval filter = flowsUpdatesFilter {\n// ...\n}\nbot.setWebhookInfoAndStartListenWebhooks(\n8080, // listening port. It is required for cases when your server hidden by some proxy or other system like Heroku\nCIO, // 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\nSetWebhook(\n\"address.com/webhook_route\",\nFile(\"/path/to/certificate\").toInputFile(), // certificate file. More info here: https://core.telegram.org/bots/webhooks#a-certificate-where-do-i-get-one-and-how\n40, // max allowed updates, by default is null\nfilter.allowedUpdates\n),\n{\nit.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\nWebhookPrivateKeyConfig( // 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),\nscope, // Kotlin coroutine scope for internal transforming of media groups\nfilter.asUpdateReceiver\n)\n
If you will use previous example, ktor server will bind and listen url 0.0.0.0:8080/subroute and telegram will send requests to address address.com/webhook_route with custom certificate. Alternative variant will use the other SetWebhook request variant:
0.0.0.0:8080/subroute
address.com/webhook_route
SetWebhook
SetWebhook(\n\"address.com/webhook_route\",\n\"some_file_bot_id\".toInputFile(),\n40, // max allowed updates, by default is null\nfilter.allowedUpdates\n)\n
As a result, request SetWebhook will be executed and after this server will start its working and handling of updates.
This function is working almost exactly like previous example, but this one will not set up webhook info in telegram:
val filter = flowsUpdatesFilter {\n// ...\n}\nstartListenWebhooks(\n8080, // listening port. It is required for cases when your server hidden by some proxy or other system like Heroku\nCIO, // 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{\nit.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\nWebhookPrivateKeyConfig( // 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),\nscope, // Kotlin coroutine scope for internal transforming of media groups\nfilter.asUpdateReceiver\n)\n
The result will be the same as in previous example: server will start its working and handling of updates on 0.0.0.0:8080/subroute. The difference here is that in case if this bot must not answer or send some requiests - it will not be necessary to create bot for receiving of updates.
includeWebhookHandlingInRoute
includeWebhookHandlingInRouteWithFlows
For these extensions you will need to start your server manualy. In common case it will look like:
val scope = CoroutineScope(Dispatchers.Default)\nval filter = flowsUpdatesFilter {\n// ...\n}\nval environment = applicationEngineEnvironment {\nmodule {\nrouting {\nincludeWebhookHandlingInRoute(\nscope,\n{\nit.printStackTrace()\n},\nfilter.asUpdateReceiver\n)\n}\n}\nconnector {\nhost = \"0.0.0.0\"\nport = 8080\n}\n}\nembeddedServer(CIO, environment).start(true) // will start server and wait its stoping\n
In the example above server will started and binded for listening on 0.0.0.0:8080.
0.0.0.0:8080