Updates with flows¶
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.
Phylosophy of Flow updates retrieving¶
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
flowsUpdatesFilteryou will set up updates handling in the lambda passed to this factory) - Provide updates to this filter with filter#asUpdateReceiver object
Let’s look how it works with the factory above:
// Step 1 - create filter
val filter = flowsUpdatesFilter {
// Step 2 - set up handling. In this case we will print any message from group or user in console
messageFlow.onEach {
println(it)
}.launchIn(someCoroutineScope)
}
// Step 3 - passing updates to filter
bot.getUpdates().forEach {
filter.asUpdatesReceiver(it)
}
Long polling¶
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")
bot.longPolling {
messageFlow.onEach {
println(it)
}.launchIn(someCoroutineScope)
}.join()
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 😊longPollingfunction returnsJoband you may use it to:cancelworking of long polling (just calljob.cancel())joinand wait while the work oflongPollingwill not be completed (it will works infinity if you will not cancel it anywhere)- FlowsUpdatesFilter has been created under the hood of
longPollingfunction
Results and What is next?¶
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
- FSM variant of Behaviour Builder