diff --git a/example/pom.xml b/example/pom.xml index 2817aae..1a3ac8c 100644 --- a/example/pom.xml +++ b/example/pom.xml @@ -26,7 +26,7 @@ it.tdlight tdlight-java-bom - 3.1.3+td.1.8.16 + 3.1.4+td.1.8.17 pom import diff --git a/example/src/main/java/it/tdlight/example/AdvancedExample.java b/example/src/main/java/it/tdlight/example/AdvancedExample.java index 6cc1839..fa487a8 100644 --- a/example/src/main/java/it/tdlight/example/AdvancedExample.java +++ b/example/src/main/java/it/tdlight/example/AdvancedExample.java @@ -1,6 +1,8 @@ package it.tdlight.example; import it.tdlight.Init; +import it.tdlight.Log; +import it.tdlight.Slf4JLogMessageHandler; import it.tdlight.TelegramClient; import it.tdlight.jni.TdApi; import it.tdlight.ClientFactory; @@ -15,6 +17,9 @@ public class AdvancedExample { // Initialize TDLight native libraries Init.init(); + // Set the log level + Log.setLogMessageHandler(1, new Slf4JLogMessageHandler()); + // Create a client manager, it should be closed before shutdown ClientFactory clientManager = ClientFactory.create(); diff --git a/example/src/main/java/it/tdlight/example/Example.java b/example/src/main/java/it/tdlight/example/Example.java index 57d224e..04efa16 100644 --- a/example/src/main/java/it/tdlight/example/Example.java +++ b/example/src/main/java/it/tdlight/example/Example.java @@ -9,15 +9,17 @@ import it.tdlight.client.TDLibSettings; import it.tdlight.Init; import it.tdlight.Slf4JLogMessageHandler; import it.tdlight.jni.TdApi.AuthorizationState; -import it.tdlight.jni.TdApi.Chat; import it.tdlight.jni.TdApi.FormattedText; import it.tdlight.jni.TdApi.InputMessageText; +import it.tdlight.jni.TdApi.Message; import it.tdlight.jni.TdApi.MessageContent; import it.tdlight.jni.TdApi; +import it.tdlight.jni.TdApi.MessageSenderUser; import it.tdlight.jni.TdApi.SendMessage; import it.tdlight.jni.TdApi.TextEntity; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.concurrent.TimeUnit; /** * Example class for TDLight Java @@ -26,14 +28,9 @@ import java.nio.file.Paths; */ public final class Example { - /** - * Admin user id, used by the stop command example - */ - private static final TdApi.MessageSender ADMIN_ID = new TdApi.MessageSenderUser(667900586); - - private static SimpleTelegramClient CLIENT; - public static void main(String[] args) throws Exception { + long adminId = Integer.getInteger("it.tdlight.example.adminid", 667900586); + // Initialize TDLight native libraries Init.init(); @@ -66,21 +63,10 @@ public final class Example { // This is an example, remove this line to use the real telegram datacenters! settings.setUseTestDatacenter(true); - // Add an example update handler that prints when the bot is started - clientBuilder.addUpdateHandler(TdApi.UpdateAuthorizationState.class, Example::onUpdateAuthorizationState); - - // Add an example update handler that prints every received message - clientBuilder.addUpdateHandler(TdApi.UpdateNewMessage.class, Example::onUpdateNewMessage); - - // Add an example command handler that stops the bot - clientBuilder.addCommandHandler("stop", new StopCommandHandler()); - // Create and start the client - SimpleTelegramClient client = CLIENT = clientBuilder.build(authenticationData); - try (client) { - + try (var app = new ExampleApp(clientBuilder, authenticationData, adminId)) { // Get me - TdApi.User me = client.getMeAsync().join(); + TdApi.User me = app.getClient().getMeAsync().get(1, TimeUnit.MINUTES); // Send a test message var req = new SendMessage(); @@ -88,80 +74,127 @@ public final class Example { var txt = new InputMessageText(); txt.text = new FormattedText("TDLight test", new TextEntity[0]); req.inputMessageContent = txt; - var result = client.sendMessage(req, true).join(); + Message result = app.getClient().sendMessage(req, true).get(1, TimeUnit.MINUTES); System.out.println("Sent message:" + result); - - // Wait for exit - client.waitForExit(); - }; - } - } - - /** - * Print new messages received via updateNewMessage - */ - private static void onUpdateNewMessage(TdApi.UpdateNewMessage update) { - // Get the message content - MessageContent messageContent = update.message.content; - - // Get the message text - String text; - if (messageContent instanceof TdApi.MessageText 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.getClass().getSimpleName()); - } - - // Get the chat title - CLIENT.send(new TdApi.GetChat(update.message.chatId), chatIdResult -> { - // Get the chat response - Chat chat = chatIdResult.get(); - // Get the chat name - String 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 static class StopCommandHandler implements CommandHandler { - - @Override - public void onCommand(TdApi.Chat chat, TdApi.MessageSender commandSender, String arguments) { - // Check if the sender is the admin - if (isAdmin(commandSender)) { - // Stop the client - System.out.println("Received stop command. closing..."); - CLIENT.sendClose(); } } } - /** - * Print the bot status - */ - private static void onUpdateAuthorizationState(TdApi.UpdateAuthorizationState update) { - AuthorizationState authorizationState = update.authorizationState; - if (authorizationState instanceof TdApi.AuthorizationStateReady) { - System.out.println("Logged in"); - } else if (authorizationState instanceof TdApi.AuthorizationStateClosing) { - System.out.println("Closing..."); - } else if (authorizationState instanceof TdApi.AuthorizationStateClosed) { - System.out.println("Closed"); - } else if (authorizationState instanceof TdApi.AuthorizationStateLoggingOut) { - System.out.println("Logging out..."); - } - } + public static class ExampleApp implements AutoCloseable { + + private final SimpleTelegramClient client; + + /** + * Admin user id, used by the stop command example + */ + private final long adminId; + + public ExampleApp(SimpleTelegramClientBuilder clientBuilder, + SimpleAuthenticationSupplier authenticationData, + long adminId) { + this.adminId = adminId; + + // Add an example update handler that prints when the bot is started + clientBuilder.addUpdateHandler(TdApi.UpdateAuthorizationState.class, this::onUpdateAuthorizationState); + + // Add an example command handler that stops the bot + clientBuilder.addCommandHandler("stop", new StopCommandHandler()); + + // Add an example update handler that prints every received message + clientBuilder.addUpdateHandler(TdApi.UpdateNewMessage.class, this::onUpdateNewMessage); + + // Build the client + this.client = clientBuilder.build(authenticationData); + } + + @Override + public void close() throws Exception { + client.close(); + } + + public SimpleTelegramClient getClient() { + return client; + } + + /** + * Print the bot status + */ + private void onUpdateAuthorizationState(TdApi.UpdateAuthorizationState update) { + AuthorizationState authorizationState = update.authorizationState; + if (authorizationState instanceof TdApi.AuthorizationStateReady) { + System.out.println("Logged in"); + } else if (authorizationState instanceof TdApi.AuthorizationStateClosing) { + System.out.println("Closing..."); + } else if (authorizationState instanceof TdApi.AuthorizationStateClosed) { + System.out.println("Closed"); + } else if (authorizationState instanceof TdApi.AuthorizationStateLoggingOut) { + System.out.println("Logging out..."); + } + } + + /** + * Print new messages received via updateNewMessage + */ + private void onUpdateNewMessage(TdApi.UpdateNewMessage update) { + // Get the message content + MessageContent messageContent = update.message.content; + + // Get the message text + String text; + if (messageContent instanceof TdApi.MessageText 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.getClass().getSimpleName()); + } + + long chatId = update.message.chatId; + + // Get the chat title + client.send(new TdApi.GetChat(chatId)) + .thenApply(chatIdResult -> { + // Get the chat name + return chatIdResult.title; + }) + .whenComplete((chatTitle, error) -> { + if (error != null) { + // Print error + System.err.printf("Can't get chat title of chat %s%n", chatId); + error.printStackTrace(System.err); + } else { + // Print the message + System.out.printf("Received new message from chat %s (%s): %s%n", chatTitle, chatId, text); + } + }); + } + + /** + * Close the bot if the /stop command is sent by the administrator + */ + private class StopCommandHandler implements CommandHandler { + + @Override + public void onCommand(TdApi.Chat chat, TdApi.MessageSender commandSender, String arguments) { + // Check if the sender is the admin + if (isAdmin(commandSender)) { + // Stop the client + System.out.println("Received stop command. closing..."); + client.sendClose(); + } + } + } + + /** + * Check if the command sender is admin + */ + public boolean isAdmin(TdApi.MessageSender sender) { + if (sender instanceof MessageSenderUser messageSenderUser) { + return messageSenderUser.userId == adminId; + } else { + return false; + } + } - /** - * Check if the command sender is admin - */ - private static boolean isAdmin(TdApi.MessageSender sender) { - return sender.equals(ADMIN_ID); } } \ No newline at end of file