TelegramBotAPI

This library is a framework for working with different workarounds for Telegram Bot API https://github.com/InsanusMokrassar/TelegramBotAPI

Introduction tutorial

It is step-by-step tutorial about how to start to write your first bot and what you should know about TelegramBotAPI library

Introduction tutorial

Before any bot project

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

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

Next steps

Introduction tutorial

Including in your project

There are three projects:

TelegramBotAPI
Also, there is an aggregator-version TelegramBotAPI, 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

Notice about repository

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

build.gradle
mavenCentral()
pom.xml
<repository>
  <id>central</id>
  <name>mavenCentral</name>
  <url>https://repo1.maven.org/maven2</url>
</repository>
Dev channel

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

Gradle
maven {
    url "https://git.inmo.dev/api/packages/InsanusMokrassar/maven"
}
Maven
<repository>
  <id>dev.inmo</id>
  <name>InmoDev</name>
  <url>https://git.inmo.dev/api/packages/InsanusMokrassar/maven</url>
</repository>

TelegramBotAPI

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

Maven Central

build.gradle
implementation "dev.inmo:tgbotapi:$tgbotapi_version"
pom.xml
<dependency>
    <groupId>dev.inmo</groupId>
    <artifactId>tgbotapi</artifactId>
    <version>${tgbotapi_version}</version>
</dependency>

TelegramBotAPI Core

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

Maven Central

build.gradle
implementation "dev.inmo:tgbotapi.core:$tgbotapi_version"
pom.xml
<dependency>
    <groupId>dev.inmo</groupId>
    <artifactId>tgbotapi.core</artifactId>
    <version>${tgbotapi_version}</version>
</dependency>

TelegramBotAPI API Extensions

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

Maven Central

build.gradle
implementation "dev.inmo:tgbotapi.api:$tgbotapi_version"
pom.xml
<dependency>
    <groupId>dev.inmo</groupId>
    <artifactId>tgbotapi.api</artifactId>
    <version>${tgbotapi_version}</version>
</dependency>

TelegramBotAPI Utils Extensions

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

Maven Central

build.gradle
implementation "dev.inmo:tgbotapi.utils:$tgbotapi_version"
pom.xml
<dependency>
    <groupId>dev.inmo</groupId>
    <artifactId>tgbotapi.utils</artifactId>
    <version>${tgbotapi_version}</version>
</dependency>

Next steps

Introduction tutorial

Proxy setup

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
	at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
	at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
	at io.ktor.network.sockets.SocketImpl.connect$ktor_network(SocketImpl.kt:36)
	at io.ktor.network.sockets.SocketImpl$connect$1.invokeSuspend(SocketImpl.kt)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)
	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:738)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)

Process finished with exit code 1

There are several ways to solve this problem:

Using Ktor Client built-in proxy

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

build.gradle:

implementation "io.ktor:ktor-client-okhttp:2.0.1"

Dependency note
In the snippet above was used version 2.0.1 which is actual for TelegramBotAPI at the moment of filling this documentation (May 22 2022, TelegramBotAPI version 2.0.0) and you can update version of this dependency in case if it is outdated.

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

val botToken = "HERE MUST BE YOUR TOKEN"
val bot = telegramBot(botToken) {
  ktorClientEngineFactory = OkHttp
  proxy = ProxyBuilder.socks("127.0.0.1", 1080)
}

Explanation line by line:

  1. val botToken = "HERE MUST BE YOUR TOKEN" - here we are just creating variable botToken
  2. val bot = telegramBot(botToken) { - start creating bot
  3. 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
  4. 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

Next steps

Introduction tutorial

First bot

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

The most simple bot

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) {
  val botToken = args.first()
  val bot = telegramBot(botToken)
  println(bot.getMe())
}

So, let's get understanding, about what is going on:

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

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

ExtendedBot(id=ChatId(chatId=123456789), username=Username(username=@first_test_ee17e8_bot), firstName=Your bot name, lastName=, canJoinGroups=false, canReadAllGroupMessages=false, supportsInlineQueries=false)

Updates retrieving

In this chapter you will learn which ways currently implemented in library and how you can use it in different situations

Updates retrieving

Updates filters

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

UpdatesFilter

UpdatesFilter currently have two properties:

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

SimpleUpdatesFilter

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

SimpleUpdatesFilter {
  println(it)
}

FlowsUpdatesFilter

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)
flowsUpdatesFilter {
  messageFlow.onEach {
    println(it)
  }.launchIn(scope)
}

Combining of flows

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:

flowsUpdatesFilter {
  (messageFlow + channelPostFlow).onEach {
    println(it) // will be printed each message update from channels and chats both
  }.launchIn(scope)
}
flowsUpdatesFilter {
  aggregateFlows(
    scope,
    messageFlow,
    channelPostFlow
  ).onEach {
    println(it) // will be printed each message update from channels and chats both
  }.launchIn(scope)
}
flowsUpdatesFilter {
  allSentMessagesFlow.onEach {
    println(it) // will be printed each message update from channels and chats both
  }.launchIn(scope)
}

Types filtering

FlowsUpdatesFilter have a lot of extensions for messages types filtering:

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

The same things were created for media groups:

flowsUpdatesFilter {
  mediaGroupMessages(scope).onEach {
    println(it) // will be printed each media group messages list from both channels and chats without filtering of content
  }.launchIn(scope)

  mediaGroupPhotosMessages(scope).onEach {
    println(it) // will be printed each media group messages list from both channels and chats with PhotoContent only
  }.launchIn(scope)

  mediaGroupVideosMessages(scope).onEach {
    println(it) // will be printed each media group messages list from both channels and chats with VideoContent only
  }.launchIn(scope)
}

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

flowsUpdatesFilter {
  sentMessagesWithMediaGroups(scope).onEach {
    println(it) // will be printed each message including each separated media group message from both channels and chats without filtering of content
  }.launchIn(scope)

  photoMessagesWithMediaGroups(scope).onEach {
    println(it) // will be printed each message including each separated media group message from both channels and chats with PhotoContent only
  }.launchIn(scope)

  videoMessagesWithMediaGroups(scope).onEach {
    println(it) // will be printed each message including each separated media group message from both channels and chats with VideoContent only
  }.launchIn(scope)
}

See also

Updates retrieving

Long polling

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.

Long polling in this library

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

longPolling

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

val bot = telegramBot(token)
bot.longPolling(
  textMessages().subscribe(scope) { // here "scope" is a CoroutineScope
    println(it) // will be printed each update from chats with messages
  }
)

startGettingOfUpdatesByLongPolling

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

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

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

val bot = telegramBot(token)
bot.startGettingOfUpdatesByLongPolling {
  println(it) // will be printed each update
}

See also

Updates retrieving

Webhooks

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:

setWebhookInfoAndStartListenWebhooks

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

val bot = telegramBot(TOKEN)

val filter = flowsUpdatesFilter {
  // ...
}

bot.setWebhookInfoAndStartListenWebhooks(
  8080, // listening port. It is required for cases when your server hidden by some proxy or other system like Heroku
  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
  SetWebhook(
    "address.com/webhook_route",
    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
    40, // max allowed updates, by default is null
    filter.allowedUpdates
  ),
  {
    it.printStackTrace() // optional handling of exceptions
  },
  "0.0.0.0", // listening host which will be used to bind by server
  "subroute", // Optional subroute, if null - will listen root of address
  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
    "/path/to/keystore.jks",
    "KeystorePassword",
    "Keystore key alias name",
    "KeystoreAliasPassword"
  ),
  scope, // Kotlin coroutine scope for internal transforming of media groups
  filter.asUpdateReceiver
)

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(
  "address.com/webhook_route",
  "some_file_bot_id".toInputFile(),
  40, // max allowed updates, by default is null
  filter.allowedUpdates
)

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

startListenWebhooks

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

val filter = flowsUpdatesFilter {
  // ...
}

startListenWebhooks(
  8080, // listening port. It is required for cases when your server hidden by some proxy or other system like Heroku
  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
  {
    it.printStackTrace() // optional handling of exceptions
  },
  "0.0.0.0", // listening host which will be used to bind by server
  "subroute", // Optional subroute, if null - will listen root of address
  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
    "/path/to/keystore.jks",
    "KeystorePassword",
    "Keystore key alias name",
    "KeystoreAliasPassword"
  ),
  scope, // Kotlin coroutine scope for internal transforming of media groups
  filter.asUpdateReceiver
)

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.

Extensions includeWebhookHandlingInRoute and includeWebhookHandlingInRouteWithFlows

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

val scope = CoroutineScope(Dispatchers.Default)

val filter = flowsUpdatesFilter {
  // ...
}

val environment = applicationEngineEnvironment {
  module {
    routing {
      includeWebhookHandlingInRoute(
        scope,
        {
          it.printStackTrace()
        },
        filter.asUpdateReceiver
      )
    }
  }
  connector {
    host = "0.0.0.0"
    port = 8080
  }
}

embeddedServer(CIO, environment).start(true) // will start server and wait its stoping

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

See also

Updates retrieving

Heroku

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

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

Short example with Behaviour Builder

suspend fun main {
    // This subroute will be used as random webhook subroute to improve security according to the recommendations of Telegram
    val subroute = uuid4().toString()
    // Input/Output coroutines scope more info here: https://kotlinlang.org/docs/coroutines-guide.html
    val scope = CoroutineScope(Dispatchers.IO)
    // Here will be automatically created bot and available inside of lambda where you will setup your bot behaviour
    telegramBotWithBehaviour(
        // Pass TOKEN inside of your application environment variables
        System.getenv("TOKEN"),
        scope = scope
    ) {
        // Set up webhooks and start to listen them
        setWebhookInfoAndStartListenWebhooks(
        	// Automatic env which will be passed by heroku to the app
            System.getenv("PORT").toInt(),
        	// Server engine. More info here: https://ktor.io/docs/engines.html
            Tomcat,
        	// Pass URL environment variable via settings of application. It must looks like https://<app name>.herokuapp.com
            SetWebhook("${System.getenv("URL").removeSuffix("/")}/$subroute"),
            // Just callback which will be called when exceptions will happen inside of webhooks
            {
                it.printStackTrace()
            },
            // Set up listen requests from outside
            "0.0.0.0",
            // Set up subroute to listen webhooks to
            subroute,
            // BehaviourContext is the CoroutineScope and it is recommended to pass it inside of webhooks server
            scope = this,
            // BehaviourContext is the FlowsUpdatesFilter and it is recommended to pass its asUpdateReceiver as a block to retrieve all the updates
            block = asUpdateReceiver
        )
      	// Test reaction on each command with reply and text `Got it`
        onUnhandledCommand {
            reply(it, "Got it")
        }
    }
  	// Just potentially infinite await of bot completion
    scope.coroutineContext.job.join()
}

Configuration example without Behaviour Builder

// This subroute will be used as random webhook subroute to improve security according to the recommendations of Telegram
val subroute = uuid4().toString()
val bot = telegramBot(TOKEN)
val scope = CoroutineScope(Dispatchers.Default)

val filter = flowsUpdatesFilter {
  messageFlow.onEach {
    println(it) // will be printed 
  }.launchIn(scope)
}

val subroute = UUID.randomUUID().toString() // It will be used as subpath for security target as recommended by https://core.telegram.org/bots/api#setwebhook

val server = bot.setWebhookInfoAndStartListenWebhooks(
  // Automatic env which will be passed by heroku to the app
  System.getenv("PORT").toInt(),
  // Server engine. More info here: https://ktor.io/docs/engines.html
  Tomcat,
  // Pass URL environment variable via settings of application. It must looks like https://<app name>.herokuapp.com
  SetWebhook("${System.getenv("URL").removeSuffix("/")}/$subroute"),
  // Just callback which will be called when exceptions will happen inside of webhooks
  {
    it.printStackTrace()
  },
  // Set up listen requests from outside
  "0.0.0.0",
  // Set up subroute to listen webhooks to
  subroute,
  scope = scope,
  block = filter.asUpdateReceiver
)

server.environment.connectors.forEach {
  println(it)
}
server.start(false)

Logic handling

In this chapter you will learn different ways to handle your bot logic

Logic handling

Exceptions handling

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

"In place" handling

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

Catching with result

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

safelyWithResult {
    // do something
}.onSuccess { // will be called if everything is right
    // handle success
}.onFailure { // will be called if something went wrong
    // handle error
    it.printStackTrace()
}.getOrThrow() // will return value or throw exception

Catching with callback

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

safely(
  {
      // handle error
      it.printStackTrace()
      null // return value
  }
) {
    // do something
}

Bonus: different types of handling

There are two types of handling:

safely(
    {
        it.printStackTrace()
        "error"
    }
) {
    error("Hi :)") // emulate exception throwing
    "ok"
} // result will be with type String
safelyWithouExceptions {
    // do something
} // will returns nullable result type

Global exceptions handling

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

val bot = telegramBot("TOKEN")

bot.buildBehaviour (
    scope = scope,
    defaultExceptionsHandler = {
        it.printStackTrace()
    }
) {
    // ...
}

OR

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

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.

Logic handling

Types conversations

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: Message Diagram.png

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

As

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;
println(message.asContentMessage() ?.content)

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

Require

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

val message: Message;
println(message.requireContentMessage().content)

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

When

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

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

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

Logic handling

Low-level work with bots

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.

Base things

There are several important things in context of this library:

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

How to handle updates

As was written above, it will require some request:

val updates = bot.execute(GetUpdates())

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

What is next?

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.

Logic handling

API Extensions

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

Bot builder

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

buildBot(
    "TOKEN"
) {
  proxy = ProxyBuilder.socks(host = "127.0.0.1", port = 4001) // just an example, more info on https://ktor.io/docs/proxy.html
  ktorClientConfig = {
    // configuring of ktor client
  }
  ktorClientEngineFactory = {
   // configuring of ktor client engine 
  }
}

Downloading of files

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).

Live location

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.

What is next?

There are several things you may read next:

Logic handling

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:

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:

Results and What is next?

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

Logic handling

Behaviour Builder

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.

Main parts of Behaviour Builder

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

Initialization

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

val bot = telegramBot("TOKEN")

bot.buildBehaviour {
  onCommand("start") { // creating of trigger
    val message = it
    val content = message.content

    reply(message, "Ok, send me one photo") // send text message with replying on incoming message

    val photoContent = waitPhoto().first() // waitPhoto will return List, so, get first element

    val photo = downloadFile(photoContent) // ByteArray of photo

    // some logic with saving of photos
  }
}

Filters

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

val bot = telegramBot("TOKEN")

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

OR

val bot = telegramBot("TOKEN")

bot.buildBehaviour {
  onCommand(
    "start",
    requireOnlyCommandInMessage = true // it is default, but you can overwrite it with `requireOnlyCommandInMessage = false`
  ) {
    // ...
  }
}
Logic handling

Behaviour Builder with FSM

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

StatesMachine have two methods:

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

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

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:

Bot with FSM

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

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

telegramBotWithBehaviourAndFSMAndStartLongPolling<YourStateType>("BOT_TOKEN") {
    // here you may use any operations from BehaviourBuilder
    // here you may use any operations from BehaviourContextWithFSMBuilder like strictlyOn and others
}

Examples

Logic handling

Files handling

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

Files receiving

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

Where to get File id or url?

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;

val fileId = message.asCommonMessage() ?.withContent<MediaContent>() ?.content ?.media ?.fileId;

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.

Download files

There are three ways to download files:

Downloading with API extensions

Files (JVM/Android)

val bot: TelegramBot;
val fileId: FileId;
val outputFile: File;

bot.downloadFile(fileId, outputFile)

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;
val fileId: FileId;

val tempFile: File = bot.downloadFileToTemp(fileId)

See downloadFileToTemp extension docs to get more available options

Byte read channel

val bot: TelegramBot;
val fileId: FileId;

val bytes: ByteReadChannelAllocator = bot.downloadFileStream(fileId)

See downloadFileStream extension docs to get more available options

Byte read channel allocator

val bot: TelegramBot;
val fileId: FileId;

val bytes: ByteReadChannelAllocator = bot.downloadFileStreamAllocator(fileId)

See downloadFileStreamAllocator extension docs to get more available options

Byte arrays

val bot: TelegramBot;
val fileId: FileId;

val bytes: ByteArray = bot.downloadFile(fileId)

See downloadFile extension docs to get more available options

Low level or how does it work?

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

val bot: TelegramBot;
val fileId: FileId;

val pathedFile: PathedFile = bot.execute(GetFile(fileId))

val downloadedBytes: ByteArray = bot.execute(DownloadFile(pathedFile.filePath))

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

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

val bot: TelegramBot;
val fileId: FileId;

val pathedFile: PathedFile = bot.execute(GetFile(fileId))

val channelAllocator: ByteReadChannelAllocator = bot.execute(DownloadFileStream(pathedFile.filePath))

val byteReadChannel: ByteReadChannel = channelAllocator()

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

Several useful liinks

Files sending

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

FileId and FileUrl

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

Sending via file

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

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

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

val file: File;

bot.sendDocument(chatId, file.asMultipartFile())
Logic handling

Media Groups

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

Specific of media groups in libraries

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(
  "token"
) {
  onVisualGallery { // it: CommonMessage<MediaGroupContent<VisualMediaGroupPartContent>>
    it.content // MediaGroupContent<VisualMediaGroupPartContent>
    it.content.group // List<MediaGroupCollectionContent.PartWrapper<VisualMediaGroupPartContent>>
    it.content.group.forEach { // it: MediaGroupCollectionContent.PartWrapper<VisualMediaGroupPartContent>
      it.messageId // source message id for current media group part
      it.sourceMessage // source message for current media group part
      it.content // VisualMediaGroupPartContent
      println(it.content) // will print current content part info
    }
  }
}

KDocs:

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

DSLs

Here will be described DSLs available in the tgbotapi library

DSLs

Text

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

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

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

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

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 "It is regular start too it is bold as well 0 1 2 3 4 5 6 7 8 9".

DSLs

Keyboards

In the telegram system there are two types of keyboards:

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

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

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

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

// reply keyboard
replyKeyboard {
    row {
        simpleButton("7")
        simpleButton("8")
        simpleButton("9")
        simpleButton("*")
    }
    row {
        simpleButton("4")
        simpleButton("5")
        simpleButton("6")
        simpleButton("/")
    }
    row {
        simpleButton("1")
        simpleButton("2")
        simpleButton("3")
        simpleButton("-")
    }
    row {
        simpleButton("0")
        simpleButton(".")
        simpleButton("=")
        simpleButton("+")
    }
}

// inline keyboard
inlineKeyboard {
    row {
        dataButton("Get random music", "random")
    }
    row {
        urlButton("Send music to friends", "https://some.link")
    }
}
DSLs

Live Location

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

sendLiveLocation

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:

startLiveLocation

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

Besides, LiveLocationProvider contains different useful parameters about live location

handleLiveLocation

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

flow {
  var i = 0
  while (isActive) {
    val newInfo = EditLiveLocationInfo(
      latitude = i.toDouble(),
      longitude = i.toDouble(),
      replyMarkup = flatInlineKeyboard {
        dataButton("Cancel", "cancel")
      }
    )
    emit(newInfo)
    i++
    delay(10000L) // 10 seconds
  }
}
val currentMessageState = MutableStateFlow<ContentMessage<LocationContent>?>(null)
handleLiveLocation(
  it.chat.id,
  locationsFlow,
  sentMessageFlow = FlowCollector { currentMessageState.emit(it) }
)
// this code will be called after `locationsFlow` will ends

OR

scope.launch {
  handleLiveLocation(
    it.chat.id,
    locationsFlow,
    sentMessageFlow = FlowCollector { currentMessageState.emit(it) }
  )
}
// this code will be called right after launch will be completed

See our example to get more detailed sample

PlaguBot

PlaguBot

Commands plugin