Skip to content

Kotlin Telegram Bot Library for creating scalable and expandable applications with hepful features.

License

Notifications You must be signed in to change notification settings

DEHuckaKpyT/telegram-bot

Repository files navigation

Kotlin Telegram Bot

Maven Central Documentation

Telegram Bot API version GitHub License

Kotlin library for creating Telegram Bots. You can use clean version, with implementation for Spring, Ktor+Koin or create with you own implementation. It have also possibility to save state in database with Spring JPA or Exposed.

Full documentation with examples and explanations.

Example of applications in example-spring, example-ktor, example-core directories.

Why this library

  • Focused on building a dialog with the user (for example, no need to specify chatId in dialog chains).
  • Has many useful utilities (such as templating, keyboard and button creating and other).
  • Telegram API methods realization have overloads for more comfortable usage (like a chatId as String or Long).
  • Working on coroutines.
  • Has clean version or with Spring or Ktor+Koin frameworks.
  • Has possibility to save state in database with Spring JPA or Exposed.
  • Easy to write tests for your bot.

⚠️ Caveat at this moment (will be resolved) ⚠️

  • Now available only long polling (will be added webhook also).

Prerequisites

  • JDK 17 or higher
  • Kotlin 1.8 or higher
  • Gradle or Maven

Quick start

build.gradle.kts

repositories {
    mavenCentral()
}
dependencies {
    implementation("io.github.dehuckakpyt.telegrambot:telegram-bot-core:$telegram_bot_version")
}

Core version

com/example/myproject/App.kt

fun main(args: Array<String>): Unit {
    val config = TelegramBotConfig().apply {
        token = "<bot token required>"
        username = "<bot username required>"
        
        receiving {
            handling {
                startCommand()
            }
        }
    }
    val context = TelegramBotFactory.createTelegramBotContext(config)
    val updateReceiver = context.updateReceiver
    // get telegramBot, templater, buttonFactory and other from created context...
    
    updateReceiver.start()
    readlnOrNull()
    updateReceiver.stop()
}

com/example/myproject/handler/StartHandler.kt

fun BotHandling.startCommand() {
    command("/start", next = "get_name") {
        // you don't have to specify a chatId to send messages
        sendMessage("Hello, my name is ${bot.username} :-)")
        // but you can do it
        bot.sendMessage(chatId, "And what is your name?")
    }

    step("get_name") {
        sendMessage("Nice to meet you, $text!")
    }
}

Spring and Ktor+Koin

Get started in documentation.