Example TD Light Team converted in Kotlin - OTR/Kotlin-Telegram-Client GitHub Wiki

This is the same example as the official TD Light Team's example posted here but automatically converted into Kotlin using IntelliJ IDEA's or Android Studio's builtin plugin converter.

package com.example

import it.tdlight.client.APIToken
import it.tdlight.client.AuthenticationData
import it.tdlight.client.CommandHandler
import it.tdlight.client.Result
import it.tdlight.client.SimpleTelegramClient
import it.tdlight.client.TDLibSettings
import it.tdlight.common.Init
import it.tdlight.common.utils.CantLoadLibrary
import it.tdlight.jni.TdApi
import kotlin.io.path.Path


object Main {

    // Admin user id, used by the stop command example
    @JvmStatic
    private val ADMIN_ID: TdApi.MessageSender = TdApi.MessageSenderUser(667900586)

    @JvmStatic
    private var client: SimpleTelegramClient? = null

    @JvmStatic
    @Throws(CantLoadLibrary::class, InterruptedException::class)
    fun main(args: Array<String>) {
        // Initialize TDLight native libraries
        Init.start()

        // Obtain the API token
        val apiToken = APIToken.example()

        // Configure the client
        val settings = TDLibSettings.create(apiToken)

        // Configure the session directory
        val sessionPath = Path("")
        settings.databaseDirectoryPath = sessionPath.resolve("tdlib")
        settings.downloadedFilesDirectoryPath = sessionPath.resolve("downloads")

        // Create a client
        client = SimpleTelegramClient(settings)

        // Configure the authentication info
        val authenticationData = AuthenticationData.consoleLogin()

        // Add an example update handler that prints when the bot is started
        client!!.addUpdateHandler<TdApi.UpdateAuthorizationState>(
            TdApi.UpdateAuthorizationState::class.java
        ) { update: TdApi.UpdateAuthorizationState -> onUpdateAuthorizationState(update) }

        // Add an example update handler that prints every received message
        client!!.addUpdateHandler<TdApi.UpdateNewMessage>(
            TdApi.UpdateNewMessage::class.java
        ) { update: TdApi.UpdateNewMessage -> onUpdateNewMessage(update) }

        // Add an example command handler that stops the bot
        client!!.addCommandHandler<TdApi.Update>("stop", StopCommandHandler())

        // Start the client
        client!!.start(authenticationData)

        // Wait for exit
        client!!.waitForExit()
    }

    /**
     * Print new messages received via updateNewMessage
     */
    @JvmStatic
    private fun onUpdateNewMessage( update: TdApi.UpdateNewMessage): Unit {
        // Get the message content
        val messageContent = update.message.content;

        // Get the message text
        var text: String? = null
        if (messageContent is TdApi.MessageText ) {
            val messageText = messageContent as TdApi.MessageText
            // Get the text of the text message
            text = messageText.text.text;
        } else {
            // We handle only text messages, the other messages will be printed as their type
            text = String.format("(%s)", messageContent.javaClass.getSimpleName());
        }

        // Get the chat title
        client!!.send(TdApi.GetChat(update.message.chatId)) { chatIdResult: Result<TdApi.Chat> ->
            // Get the chat response
            val chat = chatIdResult.get()
            // Get the chat name
            val chatName = chat.title

            // Print the message
            System.out.printf("Received new message from chat %s: %s%n", chatName, text)
        }
    }

    /**
     * Close the bot if the /stop command is sent by the administrator
     */
    private class StopCommandHandler : CommandHandler {

        override fun onCommand(chat: TdApi.Chat, commandSender: TdApi.MessageSender, arguments: String) {
            // Check if the sender is the admin
            if (isAdmin(commandSender)) {
                // Stop the client
                println("Received stop command. closing...")
                client!!.sendClose()
            }
        }
    }

    /**
     * Print the bot status
     */
    @JvmStatic
    private fun onUpdateAuthorizationState(update: TdApi.UpdateAuthorizationState) {
        val authorizationState = update.authorizationState
        if (authorizationState is TdApi.AuthorizationStateReady) {
            println("Logged in")
        } else if (authorizationState is TdApi.AuthorizationStateClosing) {
            println("Closing...")
        } else if (authorizationState is TdApi.AuthorizationStateClosed) {
            println("Closed")
        } else if (authorizationState is TdApi.AuthorizationStateLoggingOut) {
            println("Logging out...")
        }
    }

    /**
     * Check if the command sender is admin
     */
    @JvmStatic
    private fun isAdmin(sender: TdApi.MessageSender): Boolean {
        println(sender.toString())
        return sender == ADMIN_ID
    }
}

The Same example with the same functionality but manually corrected and simplified:

package com.example

import it.tdlight.client.APIToken
import it.tdlight.client.AuthenticationData
import it.tdlight.client.CommandHandler
import it.tdlight.client.Result
import it.tdlight.client.SimpleTelegramClient
import it.tdlight.client.TDLibSettings
import it.tdlight.common.Init
import it.tdlight.jni.TdApi
import kotlin.io.path.Path

object Main {

    private val ADMIN_ID: TdApi.MessageSender = TdApi.MessageSenderUser(667900586)

    private val client: SimpleTelegramClient = SimpleTelegramClient(
        TDLibSettings.create(APIToken.example()).apply {
            databaseDirectoryPath = Path("").resolve("tdlib")
        }
    )

    fun main() {
        Init.start()
        client.apply {
            start(AuthenticationData.consoleLogin())
            addUpdateHandler(TdApi.UpdateAuthorizationState::class.java) { update -> onUpdateAuthorizationState(update) }
            addUpdateHandler(TdApi.UpdateNewMessage::class.java) { update -> onUpdateNewMessage(update) }
            // One way of passing Handler
            addCommandHandler<TdApi.Update>("stop", stopCommandHandler())
            // Another way of passing Handler
            addCommandHandler<TdApi.Update>("finish") {chat, commandSender, arguments ->
                finishCommandHandler(chat, commandSender, arguments)
            }
            waitForExit()
        }
    }

    private fun onUpdateAuthorizationState(update: TdApi.UpdateAuthorizationState) {
        when (update.authorizationState) {
            is TdApi.AuthorizationStateReady -> println("Logged in")
            is TdApi.AuthorizationStateClosing -> println("Closing...")
            is TdApi.AuthorizationStateClosed ->  println("Closed")
            is TdApi.AuthorizationStateLoggingOut ->  println("Logging out...")
            else -> println("Unsupported state: ${update.authorizationState}")
        }
    }

    private fun onUpdateNewMessage(update: TdApi.UpdateNewMessage) {
        val messageContent: TdApi.MessageContent = update.message.content
        val text: String = if (messageContent is TdApi.MessageText ) {
            messageContent.text.text
        } else {
            messageContent.javaClass.simpleName
        }

        client.send(TdApi.GetChat(update.message.chatId)) { chatIdResult: Result<TdApi.Chat> ->
            val chat = chatIdResult.get()
            val chatName = chat.title
            println("Received new message from chat $chatName: $text")
        }
    }

    private fun stopCommandHandler() = CommandHandler { chat, commandSender, arguments ->
        if (isAdmin(commandSender)) {
            // Stop the client
            println("Received stop command. closing...")
            client.sendClose()
        }
    }

    private fun finishCommandHandler(
        chat: TdApi.Chat, commandSender: TdApi.MessageSender, arguments: String
    ){
        if (isAdmin(commandSender)) {
            // Stop the client
            println("Received stop command. closing...")
            client.sendClose()
        }
    }

    private fun isAdmin(sender: TdApi.MessageSender): Boolean = sender == ADMIN_ID

}

fun main() {
    Main.main()
}
⚠️ **GitHub.com Fallback** ⚠️