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.
packagecom.exampleimportit.tdlight.client.APITokenimportit.tdlight.client.AuthenticationDataimportit.tdlight.client.CommandHandlerimportit.tdlight.client.Resultimportit.tdlight.client.SimpleTelegramClientimportit.tdlight.client.TDLibSettingsimportit.tdlight.common.Initimportit.tdlight.common.utils.CantLoadLibraryimportit.tdlight.jni.TdApiimportkotlin.io.path.Pathobject Main {
// Admin user id, used by the stop command example
@JvmStatic
privatevalADMIN_ID:TdApi.MessageSender=TdApi.MessageSenderUser(667900586)
@JvmStatic
privatevar client:SimpleTelegramClient?=null
@JvmStatic
@Throws(CantLoadLibrary::class, InterruptedException::class)
funmain(args:Array<String>) {
// Initialize TDLight native librariesInit.start()
// Obtain the API tokenval apiToken =APIToken.example()
// Configure the clientval settings =TDLibSettings.create(apiToken)
// Configure the session directoryval sessionPath =Path("")
settings.databaseDirectoryPath = sessionPath.resolve("tdlib")
settings.downloadedFilesDirectoryPath = sessionPath.resolve("downloads")
// Create a client
client =SimpleTelegramClient(settings)
// Configure the authentication infoval 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
privatefunonUpdateNewMessage( update:TdApi.UpdateNewMessage): Unit {
// Get the message contentval messageContent = update.message.content;
// Get the message textvar text:String?=nullif (messageContent isTdApi.MessageText ) {
val messageText = messageContent asTdApi.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 responseval chat = chatIdResult.get()
// Get the chat nameval chatName = chat.title
// Print the messageSystem.out.printf("Received new message from chat %s: %s%n", chatName, text)
}
}
/** * Close the bot if the /stop command is sent by the administrator*/privateclassStopCommandHandler : CommandHandler {
overridefunonCommand(chat:TdApi.Chat, commandSender:TdApi.MessageSender, arguments:String) {
// Check if the sender is the adminif (isAdmin(commandSender)) {
// Stop the clientprintln("Received stop command. closing...")
client!!.sendClose()
}
}
}
/** * Print the bot status*/
@JvmStatic
privatefunonUpdateAuthorizationState(update:TdApi.UpdateAuthorizationState) {
val authorizationState = update.authorizationState
if (authorizationState isTdApi.AuthorizationStateReady) {
println("Logged in")
} elseif (authorizationState isTdApi.AuthorizationStateClosing) {
println("Closing...")
} elseif (authorizationState isTdApi.AuthorizationStateClosed) {
println("Closed")
} elseif (authorizationState isTdApi.AuthorizationStateLoggingOut) {
println("Logging out...")
}
}
/** * Check if the command sender is admin*/
@JvmStatic
privatefunisAdmin(sender:TdApi.MessageSender): Boolean {
println(sender.toString())
return sender ==ADMIN_ID
}
}
The Same example with the same functionality but manually corrected and simplified:
packagecom.exampleimportit.tdlight.client.APITokenimportit.tdlight.client.AuthenticationDataimportit.tdlight.client.CommandHandlerimportit.tdlight.client.Resultimportit.tdlight.client.SimpleTelegramClientimportit.tdlight.client.TDLibSettingsimportit.tdlight.common.Initimportit.tdlight.jni.TdApiimportkotlin.io.path.Pathobject Main {
privatevalADMIN_ID:TdApi.MessageSender=TdApi.MessageSenderUser(667900586)
privateval client:SimpleTelegramClient=SimpleTelegramClient(
TDLibSettings.create(APIToken.example()).apply {
databaseDirectoryPath =Path("").resolve("tdlib")
}
)
funmain() {
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()
}
}
privatefunonUpdateAuthorizationState(update:TdApi.UpdateAuthorizationState) {
when (update.authorizationState) {
isTdApi.AuthorizationStateReady->println("Logged in")
isTdApi.AuthorizationStateClosing->println("Closing...")
isTdApi.AuthorizationStateClosed->println("Closed")
isTdApi.AuthorizationStateLoggingOut->println("Logging out...")
else->println("Unsupported state: ${update.authorizationState}")
}
}
privatefunonUpdateNewMessage(update:TdApi.UpdateNewMessage) {
val messageContent:TdApi.MessageContent= update.message.content
val text:String=if (messageContent isTdApi.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")
}
}
privatefunstopCommandHandler() =CommandHandler { chat, commandSender, arguments ->if (isAdmin(commandSender)) {
// Stop the clientprintln("Received stop command. closing...")
client.sendClose()
}
}
privatefunfinishCommandHandler(
chat:TdApi.Chat, commandSender:TdApi.MessageSender, arguments:String
){
if (isAdmin(commandSender)) {
// Stop the clientprintln("Received stop command. closing...")
client.sendClose()
}
}
privatefunisAdmin(sender:TdApi.MessageSender): Boolean= sender ==ADMIN_ID
}
funmain() {
Main.main()
}