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.
+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 * * * *"
+val scheduler = buildSchedule(schedule)
+
+scheduler.asFlow().onEach {
+ // this block will be called every minute at 5 seconds
+}.launchIn(someCoroutineScope)
+
In case of usage builder (lets call it lambda way), you will be able to configure scheduler in more type-safe way:
+
val scheduler = buildSchedule {
+ seconds {
+ at(5)
+ }
+}
+
+scheduler.asFlow().onEach {
+ // this block will be called every minute at 5 seconds
+}.launchIn(someCoroutineScope)
+
0/5,L * * * * for every five seconds triggering and on 59 second
+
0/15 30 * * * for every 15th seconds in a half of each hour
+
0/15 30 * * * 500ms for every 15th seconds in a half of each hour when milliseconds equal to 500
+
1 2 3 F,4,L 5 for triggering in near first second of second minute of third hour of first, fifth and last days of may
+
1 2 3 F,4,L 5 60o 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
+
1 2 3 F,4,L 5 60o 0-2w 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
+
1 2 3 F,4,L 5 2021 for triggering in near first second of second minute of third hour of first, fifth and last days of may of 2021st year
+
1 2 3 F,4,L 5 2021 60o 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
+
1 2 3 F,4,L 5 2021 60o 0-2w 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
+
1 2 3 F,4,L 5 2021 60o 0-2w 500ms 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
+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:
All executes are look like do.... All executes are described below:
+
+
doOnce - will get the next time for executing, delay until that time and call block with returning of the block result
+
doWhile - will call doOnce while it will return true (that means that block must return true if it expects that next call must happen). In two words: it will run while block returning true
+
doInfinity - will call the block using doWhile with predefined returning true. In two words: it will call block while it do not throw error
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.
+
+
AnyTimeScheduler - will always return incoming DateTime as next
+
Every*Scheduler - return near * since the passed relatively:
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 nextDateTime
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:
In the Bot API there is no independent sendLiveLocation method, instead it is suggested to use sendLocation with setting up live_period. In this library in difference with original Bot API live location is special request. It was required because of in fact live locations and static locations are different types of location info and you as bot developer may interact with them differently.
Anyway, in common case the logic looks like:
Send sendLiveLocation
Use editLiveLocation to change it during its lifetime
Use stopLiveLocation to abort it before lifetime end
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:
startLiveLocation
Use LiveLocationProvider#updateLocation to update location and optionally add inline keyboard
Use LiveLocationProvider#close to abort live location before its end
Besides, LiveLocationProvider contains different useful parameters about live location
This way of live locations handling is based on coroutines Flow and allow you to pass some external Flow with EditLiveLocationInfo. So, workflow:
Create your own flow of locations. For example:
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
In case you needed, create your collector to store the message with live location:
val currentMessageState = MutableStateFlow<ContentMessage<LocationContent>?>(null)\n
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:
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
OR
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
For the text creating there are several tools. The most simple one is to concatenate several text sources to make list of text sources as a result:
val sources = \"Regular start of text \" + bold(\"with bold part\") + italic(\"and italic ending\")\n
But there is a little bit more useful way: entities builder:
val items = (0 until 10).map { it.toString() }\nbuildEntities(\" \") {// optional \" \" auto separator which will be pasted between text sources\n +\"It is regular start too\" + bold(\"it is bold as well\")\n items.forEachIndexed { i, item ->\n if (i % 2) {\n italic(item)\n } else {\n strikethrough(item)\n }\n }\n}\n
In the code above we are creating an items list just for demonstrating that inside of buildEntities body we may use any operations for cunstructing our result list of TextSources. As a result, will be created the list which will looks like in telegram as \u201cIt is regular start too it is bold as well 0 ~~1~~ 2 ~~3~~ 4 ~~5~~ 6 ~~7~~ 8 ~~9~~\u201d.
"},{"location":"tgbotapi/introduction/before-any-bot-project.html","title":"Before any bot project","text":"
There are several places you need to visit for starting work with any Telegram Bot framework on any language:
Bots info introduction
Telegram Bot API reference (you can skip it, but it could be useful to know some specific cases in Telegram Bot API)
Anyway, the most important link is How do I create a bot? inside of Telegram Bot API
A lot of examples with using of Telegram Bot API you can find in this github repository
"},{"location":"tgbotapi/introduction/first-bot.html#the-most-simple-bot","title":"The most simple bot","text":"
The most simple bot will just print information about itself. All source code you can find in this repository. Our interest here will be concentrated on the next example part:
suspend fun main(vararg args: String) {\n val botToken = args.first()\n val bot = telegramBot(botToken)\n println(bot.getMe())\n}\n
So, let\u2019s get understanding, about what is going on:
suspend fun main(vararg args: String):
suspend required for making of requests inside of this function. For more info you can open official documentation for coroutins. In fact, suspend fun main is the same that fun main() = runBlocking {} from examples
val botToken = args.first(): here we are just getting the bot token from first arguments of command line
val bot = telegramBot(botToken) : inside of bot will be RequestsExecutor object which will be used for all requests in any project with this library
println(bot.getMe()): here happens calling of getMe extension
As a result, we will see in the command line something like
"},{"location":"tgbotapi/introduction/including-in-your-project.html","title":"Including in your project","text":"
There are three projects:
TelegramBotAPI Core - project with base for all working with Telegram Bot API
TelegramBotAPI API Extensions - extension of TelegramBotAPI with functions for more comfortable work with Telegram Bot API
TelegramBotAPI Utils Extensions - extension of TelegramBotAPI with functions for extending of different things like retrieving of updates
TelegramBotAPI
Also, there is an aggregator-version tgbotapi, which will automatically include all projects above. It is most recommended version due to the fact that it is including all necessary tools around TelegramBotAPI Core, but it is optionally due to the possible restrictions on the result methods count (for android) or bundle size
Examples
You can find full examples info in this repository. In this repository there full codes which are working in normal situation. Currently, there is only one exception when these examples could work incorrectly: you are living in the location where Telegram Bot API is unavailable. For solving this problem you can read Proxy setup part
"},{"location":"tgbotapi/introduction/including-in-your-project.html#notice-about-repository","title":"Notice about repository","text":"
To use this library, you will need to include Maven Central repository in your project
In some locations Telegram Bots API urls will be unavailable. In this case all examples will just throw exception like:
Exception in thread \"main\" java.net.ConnectException: Connection refused\n at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)\n at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)\n at io.ktor.network.sockets.SocketImpl.connect$ktor_network(SocketImpl.kt:36)\n at io.ktor.network.sockets.SocketImpl$connect$1.invokeSuspend(SocketImpl.kt)\n at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)\n at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)\n at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)\n at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:738)\n at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)\n at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)\n\nProcess finished with exit code 1\n
There are several ways to solve this problem:
Built-in proxy config (will require some socks or http proxy server)
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.
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) {\n ktorClientEngineFactory = OkHttp\n proxy = ProxyBuilder.socks(\"127.0.0.1\", 1080)\n}\n
Explanation line by line:
val botToken = \"HERE MUST BE YOUR TOKEN\" - here we are just creating variable botToken
val bot = telegramBot(botToken) { - start creating bot
ktorClientEngineFactory = OkHttp - setting up engine factory of our bot. On the time of documentation filling, OkHttp is one of the engines in Ktor system which supports socks proxy. More you can read on Ktor site in subparts about engines and proxy
proxy = ProxyBuilder.socks(\"127.0.0.1\", 1080) - here we are setting up our proxy. Here was used local server which (as assumed) will connect to server like 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.
This functionality allow you to build bot in more unified and comfortable way than standard creating with telegramBot function
buildBot(\n \"TOKEN\"\n) {\n proxy = ProxyBuilder.socks(host = \"127.0.0.1\", port = 4001) // just an example, more info on https://ktor.io/docs/proxy.html\n ktorClientConfig = {\n // configuring of ktor client\n }\n ktorClientEngineFactory = {\n // configuring of ktor client engine \n }\n}\n
"},{"location":"tgbotapi/logic/api-extensions.html#downloading-of-files","title":"Downloading of files","text":"
In standard library requests there are no way to download some file retrieved in updates or after requests. You may use syntax like bot.downloadFile(file) where file is TelegramMediaFile from telegram, FileId or even PathedFile from GetFile request (sources).
By default, you should handle updates of Live location by your code. But with extension bot#startLiveLocation you may provide all necessary startup parameters and handle updates with just calling updateLocation for retrieved LiveLocationProvider.
"},{"location":"tgbotapi/logic/api-extensions.html#what-is-next","title":"What is next?","text":"
There are several things you may read next:
Updates retrieving
Read about second level of working with library
Read about BehaviourBuilder
"},{"location":"tgbotapi/logic/behaviour-builder-with-fsm.html","title":"Behaviour Builder with FSM","text":"
Behaviour builder with FSM is based on the MicroUtils FSM. There are several important things in FSM:
State - any object which implements State interface
StateHandler (or CheckableHandlerHolder) - the handler of states
StatesMachine - some machine which work with states and handlers
StatesManager - simple manager that will solve which states to save and notify about states changes via its flows
StatesMachine have two methods:
start which will start work of machine
startChain which will add new state for handling
The most based way to create StatesMachine and register StateHandlers looks like in the next snippet:
buildFSM<TrafficLightState> {\n strictlyOn<SomeState> {\n // state handling\n }\n}.start(CoroutineScope(...)).join()\n
Full example
You may find full example of FSM usage in the tests of FSM in MicroUtils
So, you must do next steps before you will launch your bot with FSM:
Create your states. Remember that you may plan to save them, so it is likely you will need to serialize it there
Create your handlers for your states. In most cases it is useful to use CheckableHandlerHolder if you want to use standard states machine
Solve which states managers to use (the most simple one is the DefaultStatesManager with InMemoryDefaultStatesManager)
"},{"location":"tgbotapi/logic/behaviour-builder-with-fsm.html#bot-with-fsm","title":"Bot with FSM","text":"
There are several extensions for TelegramBot to create your bot with FSM:
buildBehaviourWithFSM
buildBehaviourWithFSMAndStartLongPolling
telegramBotWithBehaviourAndFSM
telegramBotWithBehaviourAndFSMAndStartLongPolling
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.
"},{"location":"tgbotapi/logic/behaviour-builder.html#main-parts-of-behaviour-builder","title":"Main parts of Behaviour Builder","text":"
There are several things you should know for better understanding of behaviour builder:
BehaviourContext - it is the thing which contains all necessary tools for working with bots
Triggers - on* extensions for BehaviourContext which allow you to create reaction on some update
Expectations (or waiters) - wait* extensions which you may use in buildBehaviour function, but it is recommended to use it in bodies of triggers
As was said above, there is buildBehaviour function which allow you set up your bot logic. Let\u2019s see an example:
val bot = telegramBot(\"TOKEN\")\n\nbot.buildBehaviour {\n onCommand(\"start\") { // creating of trigger\n val message = it\n val content = message.content\n\n reply(message, \"Ok, send me one photo\") // send text message with replying on incoming message\n\n val photoContent = waitPhoto().first() // waitPhoto will return List, so, get first element\n\n val photo = downloadFile(photoContent) // ByteArray of photo\n\n // some logic with saving of photos\n }\n}\n
In most cases there are opportunity to filter some of messages before starting of main logic. Let\u2019s look at this using the example above:
val bot = telegramBot(\"TOKEN\")\n\nbot.buildBehaviour {\n onCommand(\n \"start\",\n initialFilter = {\n it.content.textSources.size == 1 // make sure that user has sent /start without any additions\n }\n ) {\n // ...\n }\n}\n
OR
val bot = telegramBot(\"TOKEN\")\n\nbot.buildBehaviour {\n onCommand(\n \"start\",\n requireOnlyCommandInMessage = true // it is default, but you can overwrite it with `requireOnlyCommandInMessage = false`\n ) {\n // ...\n }\n}\n
In case you know, where exceptions are happening, you may use several tools for exceptions catching:
Catching with result
Catching with callback
"},{"location":"tgbotapi/logic/exceptions-handling.html#catching-with-result","title":"Catching with result","text":"
If you prefer to receive Result objects instead of some weird callbacks, you may use the next syntax:
safelyWithResult {\n // do something\n}.onSuccess { // will be called if everything is right\n // handle success\n}.onFailure { // will be called if something went wrong\n // handle error\n it.printStackTrace()\n}.getOrThrow() // will return value or throw exception\n
"},{"location":"tgbotapi/logic/exceptions-handling.html#catching-with-callback","title":"Catching with callback","text":"
Also there is more simple (in some cases) way to handle exceptions with callbacks:
"},{"location":"tgbotapi/logic/exceptions-handling.html#bonus-different-types-of-handling","title":"Bonus: different types of handling","text":"
There are two types of handling:
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:
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
Safely without exceptions - almost the same as safely, but this type by default allow to return nullable value (when exception was thrown) instead of just throwing (as with safely):
safelyWithouExceptions {\n // do something\n} // will returns nullable result type\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.
There are several cases you may need in your app to work with files:
Save FileId (for sending in future)
Download some file into memory/file in filesystem
"},{"location":"tgbotapi/logic/files-handling.html#where-to-get-file-id-or-url","title":"Where to get File id or url?","text":"
The most simple way to send some file is to get file id and send it. You may get file id from any message with media. For example, if you have received some Message, you may use asCommonMessage conversation to be able to get its content and then convert it to some content with media. Full code here:
val message: Message;\n\nval fileId = message.asCommonMessage() ?.withContent<MediaContent>() ?.content ?.media ?.fileId;\n
WAT? O.o
In the code above we get some message, safely converted it to CommonMessage with asCommonMessage, then safely took its content via withContent<MediaContent>() ?.content and then just get its media file id.
Take ByteReadChannelAllocator which allow to retrieve ByteReadChannel and do whatever you want with it
[JVM Only] Download it directly to file or temporal file
"},{"location":"tgbotapi/logic/files-handling.html#downloading-with-api-extensions","title":"Downloading with API extensions","text":""},{"location":"tgbotapi/logic/files-handling.html#files-jvmandroid","title":"Files (JVM/Android)","text":"
val bot: TelegramBot;\nval fileId: FileId;\nval outputFile: File;\n\nbot.downloadFile(fileId, outputFile)\n
See downloadFile extension docs in the JVM tab to get more available options
There is also way with saving of data into temporal file. That will allow you to do with data whatever you want without high requirements to memory or network connection:
val bot: TelegramBot;\nval fileId: FileId;\n\nval tempFile: File = bot.downloadFileToTemp(fileId)\n
See downloadFileToTemp extension docs to get more available options
val bot: TelegramBot;\nval fileId: FileId;\n\nval bytes: ByteArray = bot.downloadFile(fileId)\n
See downloadFile extension docs to get more available options
"},{"location":"tgbotapi/logic/files-handling.html#low-level-or-how-does-it-work","title":"Low level or how does it work?","text":"
You may download file with streams or with downloading into the memory first. On low level you should do several things. They are presented in next snippet:
Of course, in most cases you must be sure that file have correct type.
"},{"location":"tgbotapi/logic/files-handling.html#fileid-and-fileurl","title":"FileId and FileUrl","text":"
It is the most simple way to send any media in Telegram, but this way have several restrictions:
The FileId which has retrieved for file should not (and probably will not too) equal to the FileId retrieved by some other bot
There is a chance that the file id you are using will be expired with time
"},{"location":"tgbotapi/logic/files-handling.html#sending-via-file","title":"Sending via file","text":"
JS Restrictions
Sending via file is accessible from all supported platforms, but there is small note about JS - due to restrictions of work with streams and stream-like data (JS have no native support of files streaming) on this platform all the files will be loaded inside of RAM before the sending to the telegram services.
Sending via file is available throw the MultipartFile. There are several wayt to get it:
Simple creating via its constructor: MultipartFile(\"filename.jpg\") { /* here Input allocation */ }
Via asMultiparFile extension applicable to any ByteArray, ByteReadChannel, ByteReadChannelAllocator or File (on any platform)
In most cases, sending via files looks like in the next snippet:
val file: File;\n\nbot.sendDocument(chatId, file.asMultipartFile())\n
"},{"location":"tgbotapi/logic/low-level-work-with-bots.html","title":"Low-level work with bots","text":"
The base version of library was done a lot of time ago and just got several additions related to improvements, updates in Telegram Bot API or some requests from our community.
There are several important things in context of this library:
RequestsExecutor (also \u201cknown\u201d as TelegramBot)
Types
Requests
So, in most cases all your request calls with simplified api of this library (like bot.getMe()) will looks like bot.execute(GetMe). Result of these calls is defined in type of any request (for example, for GetMe request the result type is ExtendedBot). As a result, you can avoid any extension api (like special API extensions) and use low level request with full controlling of the whole logic flow.
"},{"location":"tgbotapi/logic/low-level-work-with-bots.html#how-to-handle-updates","title":"How to handle updates","text":"
As was written above, it will require some request:
val updates = bot.execute(GetUpdates())\n
Result type of GetUpdates request is Update. You may find inheritors of this interface in Update kdocs.
"},{"location":"tgbotapi/logic/low-level-work-with-bots.html#what-is-next","title":"What is next?","text":"
As was said above, you may look into our API extensions in case you wish to use more high-level functions instead of bot.execute(SomeRequest()). Besides, it will be very useful to know more about updates retrieving.
As you know, Telegram have the feature named Media Groups. Media groups have several differences with the common messages:
Each media group message contains special media group id
Media group may have special caption which will be visible if only the first message of media group contains caption
In most cases media groups came with long polling/webhooks in one pack
Media groups can be one of three types:
Visual (image/video)
Documents
Playlists (audio)
"},{"location":"tgbotapi/logic/media-groups.html#specific-of-media-groups-in-libraries","title":"Specific of media groups in libraries","text":"
Row updates
In tgbotapi there is no any additional handling of media groups by default and in case you will use simple bot.getUpdates, you will get the list of row updates and media groups will be included in this list as separated messages with MediaGroupPartContent. In that case you may use convertWithMediaGroupUpdates to be able to work with media groups as will be described below
In case you are using standard long polling (one of alternatives is telegramBotWithBehaviourAndLongPolling) or webhooks updates will be converted uner the hood and as a result, you will take media groups as a content in one message:
telegramBotWithBehaviourAndLongPolling(\n \"token\"\n) {\n onVisualGallery { // it: CommonMessage<MediaGroupContent<VisualMediaGroupPartContent>>\n it.content // MediaGroupContent<VisualMediaGroupPartContent>\n it.content.group // List<MediaGroupCollectionContent.PartWrapper<VisualMediaGroupPartContent>>\n it.content.group.forEach { // it: MediaGroupCollectionContent.PartWrapper<VisualMediaGroupPartContent>\n it.messageId // source message id for current media group part\n it.sourceMessage // source message for current media group part\n it.content // VisualMediaGroupPartContent\n println(it.content) // will print current content part info\n }\n }\n}\n
KDocs:
onVisualGallery
MediaGroupContent
VisualMediaGroupPartContent
MediaGroupCollectionContent.PartWrapper
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:
val message: Message;\nprintln(message.asContentMessage() ?.content)\n
This code will print null in case when message is not ContentMessage, and content when is.
when extensions will call passed block when type is correct. For example:
val message: Message;\nmessage.whenContentMessage {\n println(it.content)\n}\n
Code placed above will print content when message is ContentMessage and do nothing when not
"},{"location":"tgbotapi/logic/updates-with-flows.html","title":"Updates with flows","text":"
Of course, in most cases here we will look up the way of using utils extnsions, but you may read deeper about updates retrieving here.
"},{"location":"tgbotapi/logic/updates-with-flows.html#phylosophy-of-flow-updates-retrieving","title":"Phylosophy of Flow updates retrieving","text":"
In most updates retrieving processes there are two components: UpdatesFiler and its inheritor FlowsUpdatesFilter. It is assumed, that you will do several things in your app to handle updates:
Create your UpdatesFilter (for example, with flowsUpdatesFilter factory)
Set it up (in case of flowsUpdatesFilter you will set up updates handling in the lambda passed to this factory)
Provide updates to this filter with filter#asUpdateReceiver object
Let\u2019s look how it works with the factory above:
// Step 1 - create filter\nval filter = flowsUpdatesFilter {\n // Step 2 - set up handling. In this case we will print any message from group or user in console\n messageFlow.onEach {\n println(it)\n }.launchIn(someCoroutineScope)\n}\n\n// Step 3 - passing updates to filter\nbot.getUpdates().forEach {\n filter.asUpdatesReceiver(it)\n}\n
Some example with long polling has been described above. But it is more useful to use some factories for it. In this page we will look for simple variant with TelegramBot#longPolling. So, with this function, your handling of updates will looks like:
val bot = telegramBot(\"TOKEN\")\n\nbot.longPolling {\n messageFlow.onEach {\n println(it)\n }.launchIn(someCoroutineScope)\n}.join()\n
This example looks like the example above with three steps, but there are several important things here:
You do not manage retrieving of updates by hands
.join() will suspend your function \ud83d\ude0a longPolling function returns Job and you may use it to:
cancel working of long polling (just call job.cancel())
join and wait while the work of longPolling will not be completed (it will works infinity if you will not cancel it anywhere)
FlowsUpdatesFilter has been created under the hood of longPolling function
"},{"location":"tgbotapi/logic/updates-with-flows.html#results-and-what-is-next","title":"Results and What is next?","text":"
As a result you can start listen updates and react on it. Next recommended articles:
Behaviour Builder as a variant of asynchronous handling of your bot logic
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:
Heroku apps by default accessible via https://<app name>.herokuapp.com/
Heroku provide one port to be proxied for the link above. You can retrieve number of this port by calling System.getenv(\"PORT\").toInt()
Currently (Sat Aug 15 5:04:21 +00 2020) there is only one official server engine for ktor which is correctly working with Heroku: Tomcat server engine
Server configuration alternatives
Here will be presented variants of configuration of webhooks and starting server. You always able to set webhook manualy, create your own ktor server and include webhooks handling in it or create and start server with only webhooks handling. More info you can get on page Webhooks
"},{"location":"tgbotapi/updates/heroku.html#short-example-with-behaviour-builder","title":"Short example with Behaviour Builder","text":"
suspend fun main {\n // This subroute will be used as random webhook subroute to improve security according to the recommendations of Telegram\n val subroute = uuid4().toString()\n // Input/Output coroutines scope more info here: https://kotlinlang.org/docs/coroutines-guide.html\n val scope = CoroutineScope(Dispatchers.IO)\n // Here will be automatically created bot and available inside of lambda where you will setup your bot behaviour\n telegramBotWithBehaviour(\n // Pass TOKEN inside of your application environment variables\n System.getenv(\"TOKEN\"),\n scope = scope\n ) {\n // Set up webhooks and start to listen them\n setWebhookInfoAndStartListenWebhooks(\n // Automatic env which will be passed by heroku to the app\n System.getenv(\"PORT\").toInt(),\n // Server engine. More info here: https://ktor.io/docs/engines.html\n Tomcat,\n // Pass URL environment variable via settings of application. It must looks like https://<app name>.herokuapp.com\n SetWebhook(\"${System.getenv(\"URL\").removeSuffix(\"/\")}/$subroute\"),\n // Just callback which will be called when exceptions will happen inside of webhooks\n {\n it.printStackTrace()\n },\n // Set up listen requests from outside\n \"0.0.0.0\",\n // Set up subroute to listen webhooks to\n subroute,\n // BehaviourContext is the CoroutineScope and it is recommended to pass it inside of webhooks server\n scope = this,\n // BehaviourContext is the FlowsUpdatesFilter and it is recommended to pass its asUpdateReceiver as a block to retrieve all the updates\n block = asUpdateReceiver\n )\n // Test reaction on each command with reply and text `Got it`\n onUnhandledCommand {\n reply(it, \"Got it\")\n }\n }\n // Just potentially infinite await of bot completion\n scope.coroutineContext.job.join()\n}\n
"},{"location":"tgbotapi/updates/heroku.html#configuration-example-without-behaviour-builder","title":"Configuration example without Behaviour Builder","text":"
// This subroute will be used as random webhook subroute to improve security according to the recommendations of Telegram\nval subroute = uuid4().toString()\nval bot = telegramBot(TOKEN)\nval scope = CoroutineScope(Dispatchers.Default)\n\nval filter = flowsUpdatesFilter {\n messageFlow.onEach {\n println(it) // will be printed \n }.launchIn(scope)\n}\n\nval subroute = UUID.randomUUID().toString() // It will be used as subpath for security target as recommended by https://core.telegram.org/bots/api#setwebhook\n\nval server = bot.setWebhookInfoAndStartListenWebhooks(\n // Automatic env which will be passed by heroku to the app\n System.getenv(\"PORT\").toInt(),\n // Server engine. More info here: https://ktor.io/docs/engines.html\n Tomcat,\n // Pass URL environment variable via settings of application. It must looks like https://<app name>.herokuapp.com\n SetWebhook(\"${System.getenv(\"URL\").removeSuffix(\"/\")}/$subroute\"),\n // Just callback which will be called when exceptions will happen inside of webhooks\n {\n it.printStackTrace()\n },\n // Set up listen requests from outside\n \"0.0.0.0\",\n // Set up subroute to listen webhooks to\n subroute,\n scope = scope,\n block = filter.asUpdateReceiver\n)\n\nserver.environment.connectors.forEach {\n println(it)\n}\nserver.start(false)\n
Long polling is a technology of getting updates for cases you do not have some dedicated server or you have no opportunity to receive updates via webhooks. More about this you can read in wiki.
"},{"location":"tgbotapi/updates/long-polling.html#long-polling-in-this-library","title":"Long polling in this library","text":"
There are a lot of ways to include work with long polling:
RequestsExecutor#longPollingFlow Is the base way to get all updates cold Flow. Remember, that this flow will not be launched automatically
RequestsExecutor#startGettingOfUpdatesByLongPolling Old and almost deprecated way
RequestsExecutor#longPolling Works like startGettingOfUpdatesByLongPolling but shorted in a name :)
RequestsExecutor#createAccumulatedUpdatesRetrieverFlow Works like longPollingFlow, but flow inside will return only the updates accumulated at the moment of calls (all new updates will not be passed throw this flow)
RequestsExecutor#retrieveAccumulatedUpdates Use createAccumulatedUpdatesRetrieverFlow to perform all accumulated updates
RequestsExecutor#flushAccumulatedUpdates Works like retrieveAccumulatedUpdates but perform all updates directly in a place of calling
By yourself with GetUpdates request or RequestsExecutor#getUpdates extension
longPolling is a simple way to start getting updates and work with bot:
val bot = telegramBot(token)\nbot.longPolling(\n textMessages().subscribe(scope) { // here \"scope\" is a CoroutineScope\n println(it) // will be printed each update from chats with messages\n }\n)\n
The main aim of startGettingOfUpdatesByLongPolling extension was to provide more simple way to get updates in automatic mode:
val bot = telegramBot(token)\nbot.startGettingOfUpdatesByLongPolling(\n {\n println(it) // will be printed each update from chats with messages\n }\n)\n
The other way is to use the most basic startGettingOfUpdatesByLongPolling extension:
val bot = telegramBot(token)\nbot.startGettingOfUpdatesByLongPolling {\n println(it) // will be printed each update\n}\n
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
asUpdateReceiver - required to represent this filter as common updates receiver which able to get any Update
allowedUpdates - required to determine, which updates are usefull for this filter
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:
A little bit more modern way is to use FlowsUpdatesFilter. It is very powerfull API of Kotlin Coroutines Flows, built-in support of additional extensions for FlowsUpdatesFilter and Flow<...> receivers and opportunity to split one filter for as much receivers as you want. Filter creating example:
val scope = CoroutineScope(Dispatchers.Default)\nflowsUpdatesFilter {\n messageFlow.onEach {\n println(it)\n }.launchIn(scope)\n}\n
"},{"location":"tgbotapi/updates/updates-filters.html#combining-of-flows","title":"Combining of flows","text":"
In cases you need not separate logic for handling of messages from channels and chats there are three ways to combine different flows into one:
Standard plus operation and handling of different flows:
flowsUpdatesFilter {\n (messageFlow + channelPostFlow).onEach {\n println(it) // will be printed each message update from channels and chats both\n }.launchIn(scope)\n}\n
TelegramBotAPI library support function aggregateFlows:
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
FlowsUpdatesFilter extensions:
flowsUpdatesFilter {\n allSentMessagesFlow.onEach {\n println(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 {\n textMessages(scope).onEach {\n println(it) // will be printed each message from channels and chats both with content only `TextContent`\n }.launchIn(scope)\n}\n
The same things were created for media groups:
flowsUpdatesFilter {\n mediaGroupMessages(scope).onEach {\n println(it) // will be printed each media group messages list from both channels and chats without filtering of content\n }.launchIn(scope)\n\n mediaGroupPhotosMessages(scope).onEach {\n println(it) // will be printed each media group messages list from both channels and chats with PhotoContent only\n }.launchIn(scope)\n\n mediaGroupVideosMessages(scope).onEach {\n println(it) // will be printed each media group messages list from both channels and chats with VideoContent only\n }.launchIn(scope)\n}\n
Besides, there is an opportunity to avoid separation on media groups and common messages and receive photos and videos content in one flow:
flowsUpdatesFilter {\n sentMessagesWithMediaGroups(scope).onEach {\n println(it) // will be printed each message including each separated media group message from both channels and chats without filtering of content\n }.launchIn(scope)\n\n photoMessagesWithMediaGroups(scope).onEach {\n println(it) // will be printed each message including each separated media group message from both channels and chats with PhotoContent only\n }.launchIn(scope)\n\n videoMessagesWithMediaGroups(scope).onEach {\n println(it) // will be printed each message including each separated media group message from both channels and chats with VideoContent only\n }.launchIn(scope)\n}\n
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 for ktor server
It is the most common way to set updates webhooks and start listening of them. Example:
val bot = telegramBot(TOKEN)\n\nval filter = flowsUpdatesFilter {\n // ...\n}\n\nbot.setWebhookInfoAndStartListenWebhooks(\n 8080, // listening port. It is required for cases when your server hidden by some proxy or other system like Heroku\n CIO, // default ktor server engine. It is recommended to replace it with something like `Netty`. More info about engines here: https://ktor.io/servers/configuration.html\n SetWebhook(\n \"address.com/webhook_route\",\n File(\"/path/to/certificate\").toInputFile(), // certificate file. More info here: https://core.telegram.org/bots/webhooks#a-certificate-where-do-i-get-one-and-how\n 40, // max allowed updates, by default is null\n filter.allowedUpdates\n ),\n {\n it.printStackTrace() // optional handling of exceptions\n },\n \"0.0.0.0\", // listening host which will be used to bind by server\n \"subroute\", // Optional subroute, if null - will listen root of address\n WebhookPrivateKeyConfig( // optional config of private key. It will be installed in server to use TLS with custom certificate. More info here: https://core.telegram.org/bots/webhooks#a-certificate-where-do-i-get-one-and-how\n \"/path/to/keystore.jks\",\n \"KeystorePassword\",\n \"Keystore key alias name\",\n \"KeystoreAliasPassword\"\n ),\n scope, // Kotlin coroutine scope for internal transforming of media groups\n filter.asUpdateReceiver\n)\n
If you will use previous example, ktor server will bind and listen url 0.0.0.0:8080/subroute and telegram will send requests to address address.com/webhook_route with custom certificate. Alternative variant will use the other SetWebhook request variant:
SetWebhook(\n \"address.com/webhook_route\",\n \"some_file_bot_id\".toInputFile(),\n 40, // max allowed updates, by default is null\n filter.allowedUpdates\n)\n
As a result, request SetWebhook will be executed and after this server will start its working and handling of updates.
This function is working almost exactly like previous example, but this one will not set up webhook info in telegram:
val filter = flowsUpdatesFilter {\n // ...\n}\n\nstartListenWebhooks(\n 8080, // listening port. It is required for cases when your server hidden by some proxy or other system like Heroku\n CIO, // default ktor server engine. It is recommended to replace it with something like `Netty`. More info about engines here: https://ktor.io/servers/configuration.html\n {\n it.printStackTrace() // optional handling of exceptions\n },\n \"0.0.0.0\", // listening host which will be used to bind by server\n \"subroute\", // Optional subroute, if null - will listen root of address\n WebhookPrivateKeyConfig( // optional config of private key. It will be installed in server to use TLS with custom certificate. More info here: https://core.telegram.org/bots/webhooks#a-certificate-where-do-i-get-one-and-how\n \"/path/to/keystore.jks\",\n \"KeystorePassword\",\n \"Keystore key alias name\",\n \"KeystoreAliasPassword\"\n ),\n scope, // Kotlin coroutine scope for internal transforming of media groups\n filter.asUpdateReceiver\n)\n
The result will be the same as in previous example: server will start its working and handling of updates on 0.0.0.0:8080/subroute. The difference here is that in case if this bot must not answer or send some requiests - it will not be necessary to create bot for receiving of updates.
"},{"location":"tgbotapi/updates/webhooks.html#extensions-includewebhookhandlinginroute-and-includewebhookhandlinginroutewithflows","title":"Extensions includeWebhookHandlingInRoute and includeWebhookHandlingInRouteWithFlows","text":"
For these extensions you will need to start your server manualy. In common case it will look like:
val scope = CoroutineScope(Dispatchers.Default)\n\nval filter = flowsUpdatesFilter {\n // ...\n}\n\nval environment = applicationEngineEnvironment {\n module {\n routing {\n includeWebhookHandlingInRoute(\n scope,\n {\n it.printStackTrace()\n },\n filter.asUpdateReceiver\n )\n }\n }\n connector {\n host = \"0.0.0.0\"\n port = 8080\n }\n}\n\nembeddedServer(CIO, environment).start(true) // will start server and wait its stoping\n
In the example above server will started and binded for listening on 0.0.0.0:8080.
"}]}
\ No newline at end of file
+{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"index.html","title":"Insanus Mokrassar libraries home","text":"
Hello :) It is my libraries docs place and I glad to welcome you here. I hope, this documentation place will help you.
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.
See String format for more info about the crontab-line syntax
This way will be very useful for cases when you need to configure something via external configuration (from file on startup or via some parameter from requests, for example):
val schedule = \"5 * * * *\"\nval scheduler = buildSchedule(schedule)\n\nscheduler.asFlow().onEach {\n // this block will be called every minute at 5 seconds\n}.launchIn(someCoroutineScope)\n
In case of usage builder (lets call it lambda way), you will be able to configure scheduler in more type-safe way:
val scheduler = buildSchedule {\n seconds {\n at(5)\n }\n}\n\nscheduler.asFlow().onEach {\n // this block will be called every minute at 5 seconds\n}.launchIn(someCoroutineScope)\n
As in crontab util, this library have almost the same format of string:
Seconds Minutes Hours Days of months Months Years Timezone Offset Week days Milliseconds Range 0..59 0..59 0..23 0..30 0..11 Any Int Any Int 0..6 0..999 Suffix - - - - - - owms Optional \u274c \u274c \u274c \u274c \u274c \u2705 \u2705 \u2705 \u2705 Full syntax support \u2705 \u2705 \u2705 \u2705 \u2705 \u2705 \u274c \u2705 \u2705 Position 0 1 2 3 4 Any after months Any after months Any after months Any after months Examples 0, */15, 300, */15, 300, */15, 220, */15, 300, */5, 110, */15, 3060o (UTC+1) 0w, */2w, 4w0ms, */150ms, 300ms
0/5,L * * * * for every five seconds triggering and on 59 second
0/15 30 * * * for every 15th seconds in a half of each hour
0/15 30 * * * 500ms for every 15th seconds in a half of each hour when milliseconds equal to 500
1 2 3 F,4,L 5 for triggering in near first second of second minute of third hour of first, fifth and last days of may
1 2 3 F,4,L 5 60o 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
1 2 3 F,4,L 5 60o 0-2w 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
1 2 3 F,4,L 5 2021 for triggering in near first second of second minute of third hour of first, fifth and last days of may of 2021st year
1 2 3 F,4,L 5 2021 60o 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
1 2 3 F,4,L 5 2021 60o 0-2w 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
1 2 3 F,4,L 5 2021 60o 0-2w 500ms 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
"},{"location":"krontab/introduction/faq.html","title":"FAQ","text":""},{"location":"krontab/introduction/faq.html#how-oftern-new-versions-are-releasing","title":"How oftern new versions are releasing?","text":"
Not very often. It depend on libraries (coroutines, korlibs/klock) updates and on some new awesome, but lightweight, features coming.
"},{"location":"krontab/introduction/faq.html#where-this-library-could-be-useful","title":"Where this library could be useful?","text":"
First of all, this library will be useful for long uptime applications which have some tasks to do from time to time.
"},{"location":"krontab/introduction/faq.html#how-to-use-crontab-like-syntax","title":"How to use crontab-like syntax?","text":"
In two words, you should call buildSchedule or createSimpleScheduler:
You can read more about syntax in String format section.
"},{"location":"krontab/introduction/how-to-use.html","title":"How to use","text":""},{"location":"krontab/introduction/how-to-use.html#previous-pages","title":"Previous pages","text":"
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 {\n seconds {\n at(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:
doOnce - will get the next time for executing, delay until that time and call block with returning of the block result
doWhile - will call doOnce while it will return true (that means that block must return true if it expects that next call must happen). In two words: it will run while block returning true
doInfinity - will call the block using doWhile with predefined returning true. In two words: it will call block while it do not throw error
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.
AnyTimeScheduler - will always return incoming DateTime as next
Every*Scheduler - return near * since the passed relatively:
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 nextDateTime
"},{"location":"krontab/introduction/including-in-project.html","title":"Including in project","text":"
In two words, you must add dependency dev.inmo:krontab:$krontab_version to your project. The latest version presented by next badge:
"},{"location":"krontab/introduction/including-in-project.html#notice-about-repository","title":"Notice about repository","text":"
To use this library, you will need to include MavenCentral repository in you project
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:
In the Bot API there is no independent sendLiveLocation method, instead it is suggested to use sendLocation with setting up live_period. In this library in difference with original Bot API live location is special request. It was required because of in fact live locations and static locations are different types of location info and you as bot developer may interact with them differently.
Anyway, in common case the logic looks like:
Send sendLiveLocation
Use editLiveLocation to change it during its lifetime
Use stopLiveLocation to abort it before lifetime end
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:
startLiveLocation
Use LiveLocationProvider#updateLocation to update location and optionally add inline keyboard
Use LiveLocationProvider#close to abort live location before its end
Besides, LiveLocationProvider contains different useful parameters about live location
This way of live locations handling is based on coroutines Flow and allow you to pass some external Flow with EditLiveLocationInfo. So, workflow:
Create your own flow of locations. For example:
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
In case you needed, create your collector to store the message with live location:
val currentMessageState = MutableStateFlow<ContentMessage<LocationContent>?>(null)\n
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:
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
OR
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
For the text creating there are several tools. The most simple one is to concatenate several text sources to make list of text sources as a result:
val sources = \"Regular start of text \" + bold(\"with bold part\") + italic(\"and italic ending\")\n
But there is a little bit more useful way: entities builder:
val items = (0 until 10).map { it.toString() }\nbuildEntities(\" \") {// optional \" \" auto separator which will be pasted between text sources\n +\"It is regular start too\" + bold(\"it is bold as well\")\n items.forEachIndexed { i, item ->\n if (i % 2) {\n italic(item)\n } else {\n strikethrough(item)\n }\n }\n}\n
In the code above we are creating an items list just for demonstrating that inside of buildEntities body we may use any operations for cunstructing our result list of TextSources. As a result, will be created the list which will looks like in telegram as \u201cIt is regular start too it is bold as well 0 ~~1~~ 2 ~~3~~ 4 ~~5~~ 6 ~~7~~ 8 ~~9~~\u201d.
"},{"location":"tgbotapi/introduction/before-any-bot-project.html","title":"Before any bot project","text":"
There are several places you need to visit for starting work with any Telegram Bot framework on any language:
Bots info introduction
Telegram Bot API reference (you can skip it, but it could be useful to know some specific cases in Telegram Bot API)
Anyway, the most important link is How do I create a bot? inside of Telegram Bot API
A lot of examples with using of Telegram Bot API you can find in this github repository
"},{"location":"tgbotapi/introduction/first-bot.html#the-most-simple-bot","title":"The most simple bot","text":"
The most simple bot will just print information about itself. All source code you can find in this repository. Our interest here will be concentrated on the next example part:
suspend fun main(vararg args: String) {\n val botToken = args.first()\n val bot = telegramBot(botToken)\n println(bot.getMe())\n}\n
So, let\u2019s get understanding, about what is going on:
suspend fun main(vararg args: String):
suspend required for making of requests inside of this function. For more info you can open official documentation for coroutins. In fact, suspend fun main is the same that fun main() = runBlocking {} from examples
val botToken = args.first(): here we are just getting the bot token from first arguments of command line
val bot = telegramBot(botToken) : inside of bot will be RequestsExecutor object which will be used for all requests in any project with this library
println(bot.getMe()): here happens calling of getMe extension
As a result, we will see in the command line something like
"},{"location":"tgbotapi/introduction/including-in-your-project.html","title":"Including in your project","text":"
There are three projects:
TelegramBotAPI Core - project with base for all working with Telegram Bot API
TelegramBotAPI API Extensions - extension of TelegramBotAPI with functions for more comfortable work with Telegram Bot API
TelegramBotAPI Utils Extensions - extension of TelegramBotAPI with functions for extending of different things like retrieving of updates
TelegramBotAPI
Also, there is an aggregator-version tgbotapi, which will automatically include all projects above. It is most recommended version due to the fact that it is including all necessary tools around TelegramBotAPI Core, but it is optionally due to the possible restrictions on the result methods count (for android) or bundle size
Examples
You can find full examples info in this repository. In this repository there full codes which are working in normal situation. Currently, there is only one exception when these examples could work incorrectly: you are living in the location where Telegram Bot API is unavailable. For solving this problem you can read Proxy setup part
"},{"location":"tgbotapi/introduction/including-in-your-project.html#notice-about-repository","title":"Notice about repository","text":"
To use this library, you will need to include Maven Central repository in your project
In some locations Telegram Bots API urls will be unavailable. In this case all examples will just throw exception like:
Exception in thread \"main\" java.net.ConnectException: Connection refused\n at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)\n at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)\n at io.ktor.network.sockets.SocketImpl.connect$ktor_network(SocketImpl.kt:36)\n at io.ktor.network.sockets.SocketImpl$connect$1.invokeSuspend(SocketImpl.kt)\n at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)\n at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)\n at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)\n at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:738)\n at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)\n at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)\n\nProcess finished with exit code 1\n
There are several ways to solve this problem:
Built-in proxy config (will require some socks or http proxy server)
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.
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) {\n ktorClientEngineFactory = OkHttp\n proxy = ProxyBuilder.socks(\"127.0.0.1\", 1080)\n}\n
Explanation line by line:
val botToken = \"HERE MUST BE YOUR TOKEN\" - here we are just creating variable botToken
val bot = telegramBot(botToken) { - start creating bot
ktorClientEngineFactory = OkHttp - setting up engine factory of our bot. On the time of documentation filling, OkHttp is one of the engines in Ktor system which supports socks proxy. More you can read on Ktor site in subparts about engines and proxy
proxy = ProxyBuilder.socks(\"127.0.0.1\", 1080) - here we are setting up our proxy. Here was used local server which (as assumed) will connect to server like 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.
This functionality allow you to build bot in more unified and comfortable way than standard creating with telegramBot function
buildBot(\n \"TOKEN\"\n) {\n proxy = ProxyBuilder.socks(host = \"127.0.0.1\", port = 4001) // just an example, more info on https://ktor.io/docs/proxy.html\n ktorClientConfig = {\n // configuring of ktor client\n }\n ktorClientEngineFactory = {\n // configuring of ktor client engine \n }\n}\n
"},{"location":"tgbotapi/logic/api-extensions.html#downloading-of-files","title":"Downloading of files","text":"
In standard library requests there are no way to download some file retrieved in updates or after requests. You may use syntax like bot.downloadFile(file) where file is TelegramMediaFile from telegram, FileId or even PathedFile from GetFile request (sources).
By default, you should handle updates of Live location by your code. But with extension bot#startLiveLocation you may provide all necessary startup parameters and handle updates with just calling updateLocation for retrieved LiveLocationProvider.
"},{"location":"tgbotapi/logic/api-extensions.html#what-is-next","title":"What is next?","text":"
There are several things you may read next:
Updates retrieving
Read about second level of working with library
Read about BehaviourBuilder
"},{"location":"tgbotapi/logic/behaviour-builder-with-fsm.html","title":"Behaviour Builder with FSM","text":"
Behaviour builder with FSM is based on the MicroUtils FSM. There are several important things in FSM:
State - any object which implements State interface
StateHandler (or CheckableHandlerHolder) - the handler of states
StatesMachine - some machine which work with states and handlers
StatesManager - simple manager that will solve which states to save and notify about states changes via its flows
StatesMachine have two methods:
start which will start work of machine
startChain which will add new state for handling
The most based way to create StatesMachine and register StateHandlers looks like in the next snippet:
buildFSM<TrafficLightState> {\n strictlyOn<SomeState> {\n // state handling\n }\n}.start(CoroutineScope(...)).join()\n
Full example
You may find full example of FSM usage in the tests of FSM in MicroUtils
So, you must do next steps before you will launch your bot with FSM:
Create your states. Remember that you may plan to save them, so it is likely you will need to serialize it there
Create your handlers for your states. In most cases it is useful to use CheckableHandlerHolder if you want to use standard states machine
Solve which states managers to use (the most simple one is the DefaultStatesManager with InMemoryDefaultStatesManager)
"},{"location":"tgbotapi/logic/behaviour-builder-with-fsm.html#bot-with-fsm","title":"Bot with FSM","text":"
There are several extensions for TelegramBot to create your bot with FSM:
buildBehaviourWithFSM
buildBehaviourWithFSMAndStartLongPolling
telegramBotWithBehaviourAndFSM
telegramBotWithBehaviourAndFSMAndStartLongPolling
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.
"},{"location":"tgbotapi/logic/behaviour-builder.html#main-parts-of-behaviour-builder","title":"Main parts of Behaviour Builder","text":"
There are several things you should know for better understanding of behaviour builder:
BehaviourContext - it is the thing which contains all necessary tools for working with bots
Triggers - on* extensions for BehaviourContext which allow you to create reaction on some update
Expectations (or waiters) - wait* extensions which you may use in buildBehaviour function, but it is recommended to use it in bodies of triggers
As was said above, there is buildBehaviour function which allow you set up your bot logic. Let\u2019s see an example:
val bot = telegramBot(\"TOKEN\")\n\nbot.buildBehaviour {\n onCommand(\"start\") { // creating of trigger\n val message = it\n val content = message.content\n\n reply(message, \"Ok, send me one photo\") // send text message with replying on incoming message\n\n val photoContent = waitPhoto().first() // waitPhoto will return List, so, get first element\n\n val photo = downloadFile(photoContent) // ByteArray of photo\n\n // some logic with saving of photos\n }\n}\n
In most cases there are opportunity to filter some of messages before starting of main logic. Let\u2019s look at this using the example above:
val bot = telegramBot(\"TOKEN\")\n\nbot.buildBehaviour {\n onCommand(\n \"start\",\n initialFilter = {\n it.content.textSources.size == 1 // make sure that user has sent /start without any additions\n }\n ) {\n // ...\n }\n}\n
OR
val bot = telegramBot(\"TOKEN\")\n\nbot.buildBehaviour {\n onCommand(\n \"start\",\n requireOnlyCommandInMessage = true // it is default, but you can overwrite it with `requireOnlyCommandInMessage = false`\n ) {\n // ...\n }\n}\n
In case you know, where exceptions are happening, you may use several tools for exceptions catching:
Catching with result
Catching with callback
"},{"location":"tgbotapi/logic/exceptions-handling.html#catching-with-result","title":"Catching with result","text":"
If you prefer to receive Result objects instead of some weird callbacks, you may use the next syntax:
safelyWithResult {\n // do something\n}.onSuccess { // will be called if everything is right\n // handle success\n}.onFailure { // will be called if something went wrong\n // handle error\n it.printStackTrace()\n}.getOrThrow() // will return value or throw exception\n
"},{"location":"tgbotapi/logic/exceptions-handling.html#catching-with-callback","title":"Catching with callback","text":"
Also there is more simple (in some cases) way to handle exceptions with callbacks:
"},{"location":"tgbotapi/logic/exceptions-handling.html#bonus-different-types-of-handling","title":"Bonus: different types of handling","text":"
There are two types of handling:
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:
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
Safely without exceptions - almost the same as safely, but this type by default allow to return nullable value (when exception was thrown) instead of just throwing (as with safely):
safelyWithouExceptions {\n // do something\n} // will returns nullable result type\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.
There are several cases you may need in your app to work with files:
Save FileId (for sending in future)
Download some file into memory/file in filesystem
"},{"location":"tgbotapi/logic/files-handling.html#where-to-get-file-id-or-url","title":"Where to get File id or url?","text":"
The most simple way to send some file is to get file id and send it. You may get file id from any message with media. For example, if you have received some Message, you may use asCommonMessage conversation to be able to get its content and then convert it to some content with media. Full code here:
val message: Message;\n\nval fileId = message.asCommonMessage() ?.withContent<MediaContent>() ?.content ?.media ?.fileId;\n
WAT? O.o
In the code above we get some message, safely converted it to CommonMessage with asCommonMessage, then safely took its content via withContent<MediaContent>() ?.content and then just get its media file id.
Take ByteReadChannelAllocator which allow to retrieve ByteReadChannel and do whatever you want with it
[JVM Only] Download it directly to file or temporal file
"},{"location":"tgbotapi/logic/files-handling.html#downloading-with-api-extensions","title":"Downloading with API extensions","text":""},{"location":"tgbotapi/logic/files-handling.html#files-jvmandroid","title":"Files (JVM/Android)","text":"
val bot: TelegramBot;\nval fileId: FileId;\nval outputFile: File;\n\nbot.downloadFile(fileId, outputFile)\n
See downloadFile extension docs in the JVM tab to get more available options
There is also way with saving of data into temporal file. That will allow you to do with data whatever you want without high requirements to memory or network connection:
val bot: TelegramBot;\nval fileId: FileId;\n\nval tempFile: File = bot.downloadFileToTemp(fileId)\n
See downloadFileToTemp extension docs to get more available options
val bot: TelegramBot;\nval fileId: FileId;\n\nval bytes: ByteArray = bot.downloadFile(fileId)\n
See downloadFile extension docs to get more available options
"},{"location":"tgbotapi/logic/files-handling.html#low-level-or-how-does-it-work","title":"Low level or how does it work?","text":"
You may download file with streams or with downloading into the memory first. On low level you should do several things. They are presented in next snippet:
Of course, in most cases you must be sure that file have correct type.
"},{"location":"tgbotapi/logic/files-handling.html#fileid-and-fileurl","title":"FileId and FileUrl","text":"
It is the most simple way to send any media in Telegram, but this way have several restrictions:
The FileId which has retrieved for file should not (and probably will not too) equal to the FileId retrieved by some other bot
There is a chance that the file id you are using will be expired with time
"},{"location":"tgbotapi/logic/files-handling.html#sending-via-file","title":"Sending via file","text":"
JS Restrictions
Sending via file is accessible from all supported platforms, but there is small note about JS - due to restrictions of work with streams and stream-like data (JS have no native support of files streaming) on this platform all the files will be loaded inside of RAM before the sending to the telegram services.
Sending via file is available throw the MultipartFile. There are several wayt to get it:
Simple creating via its constructor: MultipartFile(\"filename.jpg\") { /* here Input allocation */ }
Via asMultiparFile extension applicable to any ByteArray, ByteReadChannel, ByteReadChannelAllocator or File (on any platform)
In most cases, sending via files looks like in the next snippet:
val file: File;\n\nbot.sendDocument(chatId, file.asMultipartFile())\n
"},{"location":"tgbotapi/logic/low-level-work-with-bots.html","title":"Low-level work with bots","text":"
The base version of library was done a lot of time ago and just got several additions related to improvements, updates in Telegram Bot API or some requests from our community.
There are several important things in context of this library:
RequestsExecutor (also \u201cknown\u201d as TelegramBot)
Types
Requests
So, in most cases all your request calls with simplified api of this library (like bot.getMe()) will looks like bot.execute(GetMe). Result of these calls is defined in type of any request (for example, for GetMe request the result type is ExtendedBot). As a result, you can avoid any extension api (like special API extensions) and use low level request with full controlling of the whole logic flow.
"},{"location":"tgbotapi/logic/low-level-work-with-bots.html#how-to-handle-updates","title":"How to handle updates","text":"
As was written above, it will require some request:
val updates = bot.execute(GetUpdates())\n
Result type of GetUpdates request is Update. You may find inheritors of this interface in Update kdocs.
"},{"location":"tgbotapi/logic/low-level-work-with-bots.html#what-is-next","title":"What is next?","text":"
As was said above, you may look into our API extensions in case you wish to use more high-level functions instead of bot.execute(SomeRequest()). Besides, it will be very useful to know more about updates retrieving.
As you know, Telegram have the feature named Media Groups. Media groups have several differences with the common messages:
Each media group message contains special media group id
Media group may have special caption which will be visible if only the first message of media group contains caption
In most cases media groups came with long polling/webhooks in one pack
Media groups can be one of three types:
Visual (image/video)
Documents
Playlists (audio)
"},{"location":"tgbotapi/logic/media-groups.html#specific-of-media-groups-in-libraries","title":"Specific of media groups in libraries","text":"
Row updates
In tgbotapi there is no any additional handling of media groups by default and in case you will use simple bot.getUpdates, you will get the list of row updates and media groups will be included in this list as separated messages with MediaGroupPartContent. In that case you may use convertWithMediaGroupUpdates to be able to work with media groups as will be described below
In case you are using standard long polling (one of alternatives is telegramBotWithBehaviourAndLongPolling) or webhooks updates will be converted uner the hood and as a result, you will take media groups as a content in one message:
telegramBotWithBehaviourAndLongPolling(\n \"token\"\n) {\n onVisualGallery { // it: CommonMessage<MediaGroupContent<VisualMediaGroupPartContent>>\n it.content // MediaGroupContent<VisualMediaGroupPartContent>\n it.content.group // List<MediaGroupCollectionContent.PartWrapper<VisualMediaGroupPartContent>>\n it.content.group.forEach { // it: MediaGroupCollectionContent.PartWrapper<VisualMediaGroupPartContent>\n it.messageId // source message id for current media group part\n it.sourceMessage // source message for current media group part\n it.content // VisualMediaGroupPartContent\n println(it.content) // will print current content part info\n }\n }\n}\n
KDocs:
onVisualGallery
MediaGroupContent
VisualMediaGroupPartContent
MediaGroupCollectionContent.PartWrapper
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:
val message: Message;\nprintln(message.asContentMessage() ?.content)\n
This code will print null in case when message is not ContentMessage, and content when is.
when extensions will call passed block when type is correct. For example:
val message: Message;\nmessage.whenContentMessage {\n println(it.content)\n}\n
Code placed above will print content when message is ContentMessage and do nothing when not
"},{"location":"tgbotapi/logic/updates-with-flows.html","title":"Updates with flows","text":"
Of course, in most cases here we will look up the way of using utils extnsions, but you may read deeper about updates retrieving here.
"},{"location":"tgbotapi/logic/updates-with-flows.html#phylosophy-of-flow-updates-retrieving","title":"Phylosophy of Flow updates retrieving","text":"
In most updates retrieving processes there are two components: UpdatesFiler and its inheritor FlowsUpdatesFilter. It is assumed, that you will do several things in your app to handle updates:
Create your UpdatesFilter (for example, with flowsUpdatesFilter factory)
Set it up (in case of flowsUpdatesFilter you will set up updates handling in the lambda passed to this factory)
Provide updates to this filter with filter#asUpdateReceiver object
Let\u2019s look how it works with the factory above:
// Step 1 - create filter\nval filter = flowsUpdatesFilter {\n // Step 2 - set up handling. In this case we will print any message from group or user in console\n messageFlow.onEach {\n println(it)\n }.launchIn(someCoroutineScope)\n}\n\n// Step 3 - passing updates to filter\nbot.getUpdates().forEach {\n filter.asUpdatesReceiver(it)\n}\n
Some example with long polling has been described above. But it is more useful to use some factories for it. In this page we will look for simple variant with TelegramBot#longPolling. So, with this function, your handling of updates will looks like:
val bot = telegramBot(\"TOKEN\")\n\nbot.longPolling {\n messageFlow.onEach {\n println(it)\n }.launchIn(someCoroutineScope)\n}.join()\n
This example looks like the example above with three steps, but there are several important things here:
You do not manage retrieving of updates by hands
.join() will suspend your function \ud83d\ude0a longPolling function returns Job and you may use it to:
cancel working of long polling (just call job.cancel())
join and wait while the work of longPolling will not be completed (it will works infinity if you will not cancel it anywhere)
FlowsUpdatesFilter has been created under the hood of longPolling function
"},{"location":"tgbotapi/logic/updates-with-flows.html#results-and-what-is-next","title":"Results and What is next?","text":"
As a result you can start listen updates and react on it. Next recommended articles:
Behaviour Builder as a variant of asynchronous handling of your bot logic
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:
Heroku apps by default accessible via https://<app name>.herokuapp.com/
Heroku provide one port to be proxied for the link above. You can retrieve number of this port by calling System.getenv(\"PORT\").toInt()
Currently (Sat Aug 15 5:04:21 +00 2020) there is only one official server engine for ktor which is correctly working with Heroku: Tomcat server engine
Server configuration alternatives
Here will be presented variants of configuration of webhooks and starting server. You always able to set webhook manualy, create your own ktor server and include webhooks handling in it or create and start server with only webhooks handling. More info you can get on page Webhooks
"},{"location":"tgbotapi/updates/heroku.html#short-example-with-behaviour-builder","title":"Short example with Behaviour Builder","text":"
suspend fun main {\n // This subroute will be used as random webhook subroute to improve security according to the recommendations of Telegram\n val subroute = uuid4().toString()\n // Input/Output coroutines scope more info here: https://kotlinlang.org/docs/coroutines-guide.html\n val scope = CoroutineScope(Dispatchers.IO)\n // Here will be automatically created bot and available inside of lambda where you will setup your bot behaviour\n telegramBotWithBehaviour(\n // Pass TOKEN inside of your application environment variables\n System.getenv(\"TOKEN\"),\n scope = scope\n ) {\n // Set up webhooks and start to listen them\n setWebhookInfoAndStartListenWebhooks(\n // Automatic env which will be passed by heroku to the app\n System.getenv(\"PORT\").toInt(),\n // Server engine. More info here: https://ktor.io/docs/engines.html\n Tomcat,\n // Pass URL environment variable via settings of application. It must looks like https://<app name>.herokuapp.com\n SetWebhook(\"${System.getenv(\"URL\").removeSuffix(\"/\")}/$subroute\"),\n // Just callback which will be called when exceptions will happen inside of webhooks\n {\n it.printStackTrace()\n },\n // Set up listen requests from outside\n \"0.0.0.0\",\n // Set up subroute to listen webhooks to\n subroute,\n // BehaviourContext is the CoroutineScope and it is recommended to pass it inside of webhooks server\n scope = this,\n // BehaviourContext is the FlowsUpdatesFilter and it is recommended to pass its asUpdateReceiver as a block to retrieve all the updates\n block = asUpdateReceiver\n )\n // Test reaction on each command with reply and text `Got it`\n onUnhandledCommand {\n reply(it, \"Got it\")\n }\n }\n // Just potentially infinite await of bot completion\n scope.coroutineContext.job.join()\n}\n
"},{"location":"tgbotapi/updates/heroku.html#configuration-example-without-behaviour-builder","title":"Configuration example without Behaviour Builder","text":"
// This subroute will be used as random webhook subroute to improve security according to the recommendations of Telegram\nval subroute = uuid4().toString()\nval bot = telegramBot(TOKEN)\nval scope = CoroutineScope(Dispatchers.Default)\n\nval filter = flowsUpdatesFilter {\n messageFlow.onEach {\n println(it) // will be printed \n }.launchIn(scope)\n}\n\nval subroute = UUID.randomUUID().toString() // It will be used as subpath for security target as recommended by https://core.telegram.org/bots/api#setwebhook\n\nval server = bot.setWebhookInfoAndStartListenWebhooks(\n // Automatic env which will be passed by heroku to the app\n System.getenv(\"PORT\").toInt(),\n // Server engine. More info here: https://ktor.io/docs/engines.html\n Tomcat,\n // Pass URL environment variable via settings of application. It must looks like https://<app name>.herokuapp.com\n SetWebhook(\"${System.getenv(\"URL\").removeSuffix(\"/\")}/$subroute\"),\n // Just callback which will be called when exceptions will happen inside of webhooks\n {\n it.printStackTrace()\n },\n // Set up listen requests from outside\n \"0.0.0.0\",\n // Set up subroute to listen webhooks to\n subroute,\n scope = scope,\n block = filter.asUpdateReceiver\n)\n\nserver.environment.connectors.forEach {\n println(it)\n}\nserver.start(false)\n
Long polling is a technology of getting updates for cases you do not have some dedicated server or you have no opportunity to receive updates via webhooks. More about this you can read in wiki.
"},{"location":"tgbotapi/updates/long-polling.html#long-polling-in-this-library","title":"Long polling in this library","text":"
There are a lot of ways to include work with long polling:
RequestsExecutor#longPollingFlow Is the base way to get all updates cold Flow. Remember, that this flow will not be launched automatically
RequestsExecutor#startGettingOfUpdatesByLongPolling Old and almost deprecated way
RequestsExecutor#longPolling Works like startGettingOfUpdatesByLongPolling but shorted in a name :)
RequestsExecutor#createAccumulatedUpdatesRetrieverFlow Works like longPollingFlow, but flow inside will return only the updates accumulated at the moment of calls (all new updates will not be passed throw this flow)
RequestsExecutor#retrieveAccumulatedUpdates Use createAccumulatedUpdatesRetrieverFlow to perform all accumulated updates
RequestsExecutor#flushAccumulatedUpdates Works like retrieveAccumulatedUpdates but perform all updates directly in a place of calling
By yourself with GetUpdates request or RequestsExecutor#getUpdates extension
longPolling is a simple way to start getting updates and work with bot:
val bot = telegramBot(token)\nbot.longPolling(\n textMessages().subscribe(scope) { // here \"scope\" is a CoroutineScope\n println(it) // will be printed each update from chats with messages\n }\n)\n
The main aim of startGettingOfUpdatesByLongPolling extension was to provide more simple way to get updates in automatic mode:
val bot = telegramBot(token)\nbot.startGettingOfUpdatesByLongPolling(\n {\n println(it) // will be printed each update from chats with messages\n }\n)\n
The other way is to use the most basic startGettingOfUpdatesByLongPolling extension:
val bot = telegramBot(token)\nbot.startGettingOfUpdatesByLongPolling {\n println(it) // will be printed each update\n}\n
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
asUpdateReceiver - required to represent this filter as common updates receiver which able to get any Update
allowedUpdates - required to determine, which updates are usefull for this filter
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:
A little bit more modern way is to use FlowsUpdatesFilter. It is very powerfull API of Kotlin Coroutines Flows, built-in support of additional extensions for FlowsUpdatesFilter and Flow<...> receivers and opportunity to split one filter for as much receivers as you want. Filter creating example:
val scope = CoroutineScope(Dispatchers.Default)\nflowsUpdatesFilter {\n messageFlow.onEach {\n println(it)\n }.launchIn(scope)\n}\n
"},{"location":"tgbotapi/updates/updates-filters.html#combining-of-flows","title":"Combining of flows","text":"
In cases you need not separate logic for handling of messages from channels and chats there are three ways to combine different flows into one:
Standard plus operation and handling of different flows:
flowsUpdatesFilter {\n (messageFlow + channelPostFlow).onEach {\n println(it) // will be printed each message update from channels and chats both\n }.launchIn(scope)\n}\n
TelegramBotAPI library support function aggregateFlows:
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
FlowsUpdatesFilter extensions:
flowsUpdatesFilter {\n allSentMessagesFlow.onEach {\n println(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 {\n textMessages(scope).onEach {\n println(it) // will be printed each message from channels and chats both with content only `TextContent`\n }.launchIn(scope)\n}\n
The same things were created for media groups:
flowsUpdatesFilter {\n mediaGroupMessages(scope).onEach {\n println(it) // will be printed each media group messages list from both channels and chats without filtering of content\n }.launchIn(scope)\n\n mediaGroupPhotosMessages(scope).onEach {\n println(it) // will be printed each media group messages list from both channels and chats with PhotoContent only\n }.launchIn(scope)\n\n mediaGroupVideosMessages(scope).onEach {\n println(it) // will be printed each media group messages list from both channels and chats with VideoContent only\n }.launchIn(scope)\n}\n
Besides, there is an opportunity to avoid separation on media groups and common messages and receive photos and videos content in one flow:
flowsUpdatesFilter {\n sentMessagesWithMediaGroups(scope).onEach {\n println(it) // will be printed each message including each separated media group message from both channels and chats without filtering of content\n }.launchIn(scope)\n\n photoMessagesWithMediaGroups(scope).onEach {\n println(it) // will be printed each message including each separated media group message from both channels and chats with PhotoContent only\n }.launchIn(scope)\n\n videoMessagesWithMediaGroups(scope).onEach {\n println(it) // will be printed each message including each separated media group message from both channels and chats with VideoContent only\n }.launchIn(scope)\n}\n
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 for ktor server
It is the most common way to set updates webhooks and start listening of them. Example:
val bot = telegramBot(TOKEN)\n\nval filter = flowsUpdatesFilter {\n // ...\n}\n\nbot.setWebhookInfoAndStartListenWebhooks(\n 8080, // listening port. It is required for cases when your server hidden by some proxy or other system like Heroku\n CIO, // default ktor server engine. It is recommended to replace it with something like `Netty`. More info about engines here: https://ktor.io/servers/configuration.html\n SetWebhook(\n \"address.com/webhook_route\",\n File(\"/path/to/certificate\").toInputFile(), // certificate file. More info here: https://core.telegram.org/bots/webhooks#a-certificate-where-do-i-get-one-and-how\n 40, // max allowed updates, by default is null\n filter.allowedUpdates\n ),\n {\n it.printStackTrace() // optional handling of exceptions\n },\n \"0.0.0.0\", // listening host which will be used to bind by server\n \"subroute\", // Optional subroute, if null - will listen root of address\n WebhookPrivateKeyConfig( // optional config of private key. It will be installed in server to use TLS with custom certificate. More info here: https://core.telegram.org/bots/webhooks#a-certificate-where-do-i-get-one-and-how\n \"/path/to/keystore.jks\",\n \"KeystorePassword\",\n \"Keystore key alias name\",\n \"KeystoreAliasPassword\"\n ),\n scope, // Kotlin coroutine scope for internal transforming of media groups\n filter.asUpdateReceiver\n)\n
If you will use previous example, ktor server will bind and listen url 0.0.0.0:8080/subroute and telegram will send requests to address address.com/webhook_route with custom certificate. Alternative variant will use the other SetWebhook request variant:
SetWebhook(\n \"address.com/webhook_route\",\n \"some_file_bot_id\".toInputFile(),\n 40, // max allowed updates, by default is null\n filter.allowedUpdates\n)\n
As a result, request SetWebhook will be executed and after this server will start its working and handling of updates.
This function is working almost exactly like previous example, but this one will not set up webhook info in telegram:
val filter = flowsUpdatesFilter {\n // ...\n}\n\nstartListenWebhooks(\n 8080, // listening port. It is required for cases when your server hidden by some proxy or other system like Heroku\n CIO, // default ktor server engine. It is recommended to replace it with something like `Netty`. More info about engines here: https://ktor.io/servers/configuration.html\n {\n it.printStackTrace() // optional handling of exceptions\n },\n \"0.0.0.0\", // listening host which will be used to bind by server\n \"subroute\", // Optional subroute, if null - will listen root of address\n WebhookPrivateKeyConfig( // optional config of private key. It will be installed in server to use TLS with custom certificate. More info here: https://core.telegram.org/bots/webhooks#a-certificate-where-do-i-get-one-and-how\n \"/path/to/keystore.jks\",\n \"KeystorePassword\",\n \"Keystore key alias name\",\n \"KeystoreAliasPassword\"\n ),\n scope, // Kotlin coroutine scope for internal transforming of media groups\n filter.asUpdateReceiver\n)\n
The result will be the same as in previous example: server will start its working and handling of updates on 0.0.0.0:8080/subroute. The difference here is that in case if this bot must not answer or send some requiests - it will not be necessary to create bot for receiving of updates.
"},{"location":"tgbotapi/updates/webhooks.html#extensions-includewebhookhandlinginroute-and-includewebhookhandlinginroutewithflows","title":"Extensions includeWebhookHandlingInRoute and includeWebhookHandlingInRouteWithFlows","text":"
For these extensions you will need to start your server manualy. In common case it will look like:
val scope = CoroutineScope(Dispatchers.Default)\n\nval filter = flowsUpdatesFilter {\n // ...\n}\n\nval environment = applicationEngineEnvironment {\n module {\n routing {\n includeWebhookHandlingInRoute(\n scope,\n {\n it.printStackTrace()\n },\n filter.asUpdateReceiver\n )\n }\n }\n connector {\n host = \"0.0.0.0\"\n port = 8080\n }\n}\n\nembeddedServer(CIO, environment).start(true) // will start server and wait its stoping\n
In the example above server will started and binded for listening on 0.0.0.0:8080.