Update examples

This commit is contained in:
Andrea Cavalli 2023-09-11 01:38:53 +02:00
parent 3590bf6547
commit 250dfa3a89
3 changed files with 129 additions and 91 deletions

View File

@ -26,7 +26,7 @@
<dependency>
<groupId>it.tdlight</groupId>
<artifactId>tdlight-java-bom</artifactId>
<version>3.1.3+td.1.8.16</version>
<version>3.1.4+td.1.8.17</version>
<type>pom</type>
<scope>import</scope>
</dependency>

View File

@ -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();

View File

@ -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,64 +74,52 @@ 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();
};
}
}
public static class ExampleApp implements AutoCloseable {
private final SimpleTelegramClient client;
/**
* Print new messages received via updateNewMessage
* Admin user id, used by the stop command example
*/
private static void onUpdateNewMessage(TdApi.UpdateNewMessage update) {
// Get the message content
MessageContent messageContent = update.message.content;
private final long adminId;
// 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());
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);
}
// 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();
}
public void close() throws Exception {
client.close();
}
public SimpleTelegramClient getClient() {
return client;
}
/**
* Print the bot status
*/
private static void onUpdateAuthorizationState(TdApi.UpdateAuthorizationState update) {
private void onUpdateAuthorizationState(TdApi.UpdateAuthorizationState update) {
AuthorizationState authorizationState = update.authorizationState;
if (authorizationState instanceof TdApi.AuthorizationStateReady) {
System.out.println("Logged in");
@ -158,10 +132,69 @@ public final class Example {
}
}
/**
* 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
*/
private static boolean isAdmin(TdApi.MessageSender sender) {
return sender.equals(ADMIN_ID);
public boolean isAdmin(TdApi.MessageSender sender) {
if (sender instanceof MessageSenderUser messageSenderUser) {
return messageSenderUser.userId == adminId;
} else {
return false;
}
}
}
}