telegram-bot icon indicating copy to clipboard operation
telegram-bot copied to clipboard

Telegram Bot API wrapper with handy Kotlin DSL.

Telegram bot api library logo

Kotlin Telegram Bot

Maven Central Supported version

KDocs Awesome Kotlin Badge Chat in Telegram

Kotlin based wrapper over Telegram API.

Installation

Add the MavenCentral repository to your root build.gradle.kts file:

repositories {
    mavenCentral()
}

Now add the library itself to the dependencies' module that you need it.

dependencies {
    implementation("eu.vendeli:telegram-bot:2.0.1")
}

Samples

You can see the samples in the samples' folder there you can find:

  • Conversation - An example of using Inputs and storing data in UserData.
  • Echo - Echo bot :)
  • Exception-handling - Simple example of exception handling
  • Ktor-webhook - An example of using webhook with Ktor
  • Poll - An example of how to build a bot questionnaire.

Usage

suspend fun main() {
    val bot = TelegramBot("BOT_TOKEN", "com.example.controllers")
    /**
     * Second parameter is the package in which commands/inputs will be searched.
     */

    bot.handleUpdates()
    // start long-polling listener
}

@CommandHandler(["/start"])
suspend fun start(user: User, bot: TelegramBot) {
    message { "Hello" }.send(to = user, via = bot)
}

It is also possible to process manually:

suspend fun main() {
    val bot = TelegramBot("BOT_TOKEN")

    bot.handleUpdates { update ->
        onCommand("/start") {
            message { "Hello, what's your name?" }.send(user, bot)
            bot.inputListener.set(user.id, "conversation")
        }
        inputChain("conversation") {
            message { "Nice to meet you, ${message.text}" }.send(user, bot)
            message { "What is your favorite food?" }.send(user, bot)
        }.breakIf({ message.text == "peanut butter" }) { // chain break condition
            message { "Oh, too bad, I'm allergic to it." }.send(user, bot)
            // action that will be applied when match
        }.andThen {
            // ...
        }
    }
}

It is also possible to do more advanced processing with a manual listener setting with bot.update.setListener {} function.

for webhook handling you can use any server and bot.update.handle() function (or use this function if you're directly setting listener),
and for set webhook you can use this method:

setWebhook("https://site.com").send(bot)

if you want to operate with response you can use sendAsync() instead of send() method, which returns Response:

message { "test" }.sendAsync(user, bot).await().onFailure {
    println("code: ${it.errorCode} description: ${it.description}")
}

Any async request returns a Response on which you can also use methods getOrNull() , isSuccess() , onFailure() .

More about

You can also read more information in the wiki, and you're always welcome in chat.