migration

This commit is contained in:
hdvt
2025-11-03 21:16:02 +03:00
parent 6093465f0d
commit d80d4e3b94
26 changed files with 96 additions and 610 deletions

6
.idea/AndroidProjectSystem.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AndroidProjectSystem">
<option name="providerId" value="com.android.tools.idea.GradleProjectSystem" />
</component>
</project>

7
.idea/dictionaries/project.xml generated Normal file
View File

@@ -0,0 +1,7 @@
<component name="ProjectDictionaryState">
<dictionary name="project">
<words>
<w>jsonable</w>
</words>
</dictionary>
</component>

View File

@@ -1,139 +0,0 @@
package hdvtdev.telegram.core.objects;
import hdvtdev.telegram.annotations.handlers.CallbackQueryHandler;
import hdvtdev.telegram.annotations.handlers.TextMessageHandler;
import hdvtdev.telegram.objects.CallbackQuery;
import hdvtdev.telegram.objects.Message;
import hdvtdev.telegram.objects.Update;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.CodeSource;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public abstract class ClassFinder {
private static final Set<Class<? extends Annotation>> annotationsToSearch = Set.of(TextMessageHandler.class, CallbackQueryHandler.class);
private static final Set<Class<?>> methodsArgumentType = Set.of(Message.class, Update.class, CallbackQuery.class);
private static ErrorHandler errorHandler;
public static Map<Class<?>, Map<String, InvokeMethod>> getClasses() {
Map<Class<?>, Map<String, InvokeMethod>> allMethods = new HashMap<>();
annotationsToSearch.forEach(annotation -> allMethods.put(annotation, new HashMap<>()));
CodeSource codeSource = ClassFinder.class.getProtectionDomain().getCodeSource();
if (codeSource != null) {
try {
String path = codeSource.getLocation().toURI().getPath();
File file = new File(URLDecoder.decode(path, StandardCharsets.UTF_8));
if (file.isFile() && file.getName().endsWith(".jar")) {
processJar(file, allMethods);
} else if (file.isDirectory()) {
processDirectory(file, "", allMethods);
}
} catch (Exception e) {
return Map.of();
}
}
return Collections.unmodifiableMap(allMethods);
}
private static void processDirectory(File directory, String packageName, Map<Class<?>, Map<String, InvokeMethod>> methods) {
File[] files = directory.listFiles();
if (files == null) return;
for (File file : files) {
if (file.isDirectory()) {
processDirectory(file, packageName + file.getName() + ".", methods);
} else if (file.getName().endsWith(".class")) {
String className = packageName + file.getName().replace(".class", "");
loadClass(className, methods);
}
}
}
private static void processJar(File jarFile, Map<Class<?>, Map<String, InvokeMethod>> methods) {
try (JarFile jar = new JarFile(jarFile)) {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (entry.getName().endsWith(".class")) {
String className = entry.getName()
.replace("/", ".")
.replace(".class", "");
loadClass(className, methods);
}
}
} catch (IOException ignored) {
}
}
public static Map<Class<?>, Map<String, InvokeMethod>> localScan(Class<?> cls) {
Map<Class<?>, Map<String, InvokeMethod>> allMethods = new HashMap<>();
annotationsToSearch.forEach(annotation -> allMethods.put(annotation, new HashMap<>()));
loadClass(cls.getName(), allMethods);
return allMethods;
}
private static void loadClass(String className, Map<Class<?>, Map<String, InvokeMethod>> methods) {
try {
Class<?> c = Class.forName(className);
for (Method method : c.getDeclaredMethods()) {
Class<?>[] parameters = method.getParameterTypes();
if (parameters.length != 0 && !methodsArgumentType.contains(parameters[0])) {
continue;
}
if (method.isAnnotationPresent(CallbackQueryHandler.class)) {
if (Modifier.isStatic(method.getModifiers())) {
for (String value : method.getAnnotation(CallbackQueryHandler.class).value()) {
methods.get(CallbackQueryHandler.class).put(value, new InvokeMethod(method, parameters[0]));
}
} else
System.err.println(method + " is annotated with @CallbackQueryHandler, but it is not static. For the annotation to work, the method must be static.");
}
if (method.isAnnotationPresent(TextMessageHandler.class)) {
if (Modifier.isStatic(method.getModifiers())) {
for (String value : method.getAnnotation(TextMessageHandler.class).value()) {
methods.get(TextMessageHandler.class).put(value, new InvokeMethod(method, parameters[0]));
}
} else
System.err.println(method + " is annotated with @TextMessageHandler, but it is not static. For the annotation to work, the method must be static.");
}
}
} catch (NoClassDefFoundError | UnsupportedClassVersionError | ClassNotFoundException e) {
if (errorHandler != null) errorHandler.onError(e);
}
}
public void setErrorHandler(ErrorHandler errorHandler) {
ClassFinder.errorHandler = errorHandler;
}
public interface ErrorHandler {
void onError(Throwable throwable);
}
//tod
}

View File

@@ -21,6 +21,8 @@ public interface TelegramBot {
void shutdown(); void shutdown();
void start(UpdateConsumer updateConsumer);
default CompletableFuture<File> downloadFile(TelegramFile telegramFile, Path targetDirectory) { default CompletableFuture<File> downloadFile(TelegramFile telegramFile, Path targetDirectory) {
CompletableFuture<File> completableFuture = CompletableFuture.supplyAsync(() -> awaitDownloadFile(telegramFile, targetDirectory)); CompletableFuture<File> completableFuture = CompletableFuture.supplyAsync(() -> awaitDownloadFile(telegramFile, targetDirectory));
completableFuture.exceptionally(e -> { completableFuture.exceptionally(e -> {

View File

@@ -1,23 +1,7 @@
package hdvtdev.telegram.core; package hdvtdev.telegram.core;
import hdvtdev.telegram.core.objects.ChosenInlineResult;
import hdvtdev.telegram.core.objects.InlineQuery;
import hdvtdev.telegram.core.objects.Update; import hdvtdev.telegram.core.objects.Update;
import hdvtdev.telegram.core.objects.business.BusinessConnection;
import hdvtdev.telegram.core.objects.business.BusinessMessagesDeleted;
import hdvtdev.telegram.core.objects.callback.CallbackQuery;
import hdvtdev.telegram.core.objects.chat.ChatJoinRequest;
import hdvtdev.telegram.core.objects.chat.ChatMemberUpdated;
import hdvtdev.telegram.core.objects.chatboost.ChatBoostRemoved;
import hdvtdev.telegram.core.objects.chatboost.ChatBoostUpdated;
import hdvtdev.telegram.core.objects.media.paidmedia.PaidMediaPurchased;
import hdvtdev.telegram.core.objects.message.Message;
import hdvtdev.telegram.core.objects.message.MessageReactionCountUpdated;
import hdvtdev.telegram.core.objects.message.MessageReactionUpdated;
import hdvtdev.telegram.core.objects.payment.PreCheckoutQuery;
import hdvtdev.telegram.core.objects.payment.ShippingQuery;
import hdvtdev.telegram.core.objects.poll.Poll;
import hdvtdev.telegram.core.objects.poll.PollAnswer;
import java.util.List; import java.util.List;
@@ -25,7 +9,7 @@ public interface UpdateConsumer {
void onUpdates(List<Update> updates); default void onUpdate(Update update) {}

View File

@@ -1,80 +0,0 @@
package hdvtdev.telegram.core;
import hdvtdev.telegram.core.objects.ChosenInlineResult;
import hdvtdev.telegram.core.objects.InlineQuery;
import hdvtdev.telegram.core.objects.Update;
import hdvtdev.telegram.core.objects.business.BusinessConnection;
import hdvtdev.telegram.core.objects.business.BusinessMessagesDeleted;
import hdvtdev.telegram.core.objects.callback.CallbackQuery;
import hdvtdev.telegram.core.objects.chat.ChatJoinRequest;
import hdvtdev.telegram.core.objects.chat.ChatMemberUpdated;
import hdvtdev.telegram.core.objects.chatboost.ChatBoostRemoved;
import hdvtdev.telegram.core.objects.chatboost.ChatBoostUpdated;
import hdvtdev.telegram.core.objects.media.paidmedia.PaidMediaPurchased;
import hdvtdev.telegram.core.objects.message.Message;
import hdvtdev.telegram.core.objects.message.MessageReactionCountUpdated;
import hdvtdev.telegram.core.objects.message.MessageReactionUpdated;
import hdvtdev.telegram.core.objects.payment.PreCheckoutQuery;
import hdvtdev.telegram.core.objects.payment.ShippingQuery;
import hdvtdev.telegram.core.objects.poll.Poll;
import hdvtdev.telegram.core.objects.poll.PollAnswer;
import java.util.List;
public interface UpdateHandler extends UpdateConsumer {
@Override
default void onUpdates(List<Update> updates) {
for (Update update : updates) {
if (update.hasMessage()) onMessage(update.message());
if (update.hasEditedMessage()) onEditedMessage(update.editedMessage());
if (update.hasChannelPost()) onChannelPost(update.channelPost());
if (update.hasEditedChannelPost()) onEditedChannelPost(update.editedChannelPost());
if (update.hasBusinessConnection()) onBusinessConnection(update.businessConnection());
if (update.hasBusinessMessage()) onBusinessMessage(update.businessMessage());
if (update.hasEditedBusinessMessage()) onEditedBusinessMessage(update.editedBusinessMessage());
if (update.hasDeletedBusinessMessages()) onDeletedBusinessMessages(update.businessMessagesDeleted());
if (update.hasMessageReaction()) onMessageReaction(update.messageReaction());
if (update.hasMessageReactionCount()) onMessageReactionCount(update.messageReactionCount());
if (update.hasInlineQuery()) onInlineQuery(update.inlineQuery());
if (update.hasChosenInlineResult()) onChosenInlineResult(update.chosenInlineResult());
if (update.hasCallbackQuery()) onCallbackQuery(update.callbackQuery());
if (update.hasShippingQuery()) onShippingQuery(update.shippingQuery());
if (update.hasPreCheckoutQuery()) onPreCheckoutQuery(update.preCheckoutQuery());
if (update.hasPurchasedPaidMedia()) onPaidMediaPurchased(update.paidMediaPurchased());
if (update.hasPoll()) onPoll(update.poll());
if (update.hasPollAnswer()) onPollAnswer(update.pollAnswer());
if (update.hasMyChatMember()) onMyChatMember(update.myChatMember());
if (update.hasChatMember()) onChatMember(update.chatMember());
if (update.hasChatJoinRequest()) onChatJoinRequest(update.chatJoinRequest());
if (update.hasChatBoost()) onChatBoost(update.chatBoost());
if (update.hasRemovedChatBoost()) onChatBoostRemoved(update.chatBoostRemoved());
}
}
default void onMessage(Message message) {}
default void onEditedMessage(Message message) {}
default void onChannelPost(Message message) {}
default void onEditedChannelPost(Message message) {}
default void onBusinessConnection(BusinessConnection connection) {}
default void onBusinessMessage(Message message) {}
default void onEditedBusinessMessage(Message message) {}
default void onDeletedBusinessMessages(BusinessMessagesDeleted deleted) {}
default void onMessageReaction(MessageReactionUpdated reaction) {}
default void onMessageReactionCount(MessageReactionCountUpdated count) {}
default void onInlineQuery(InlineQuery query) {}
default void onChosenInlineResult(ChosenInlineResult result) {}
default void onCallbackQuery(CallbackQuery callbackQuery) {}
default void onShippingQuery(ShippingQuery query) {}
default void onPreCheckoutQuery(PreCheckoutQuery query) {}
default void onPaidMediaPurchased(PaidMediaPurchased paidMedia) {}
default void onPoll(Poll poll) {}
default void onPollAnswer(PollAnswer answer) {}
default void onMyChatMember(ChatMemberUpdated member) {}
default void onChatMember(ChatMemberUpdated member) {}
default void onChatJoinRequest(ChatJoinRequest request) {}
default void onChatBoost(ChatBoostUpdated boost) {}
default void onChatBoostRemoved(ChatBoostRemoved removedBoost) {}
}

View File

@@ -1,19 +0,0 @@
package hdvtdev.telegram.core.annotaions;
import hdvtdev.telegram.core.methods.TelegramApiMethod;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is used to indicate {@link TelegramApiMethod} that should be serialized into JSON.
* <h5>Last documentation update: 2025-04-05</h5>
* @see com.fasterxml.jackson.databind.ObjectMapper
* @since 1.0.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Jsonable {
}

View File

@@ -8,7 +8,7 @@ import hdvtdev.telegram.core.objects.User;
/** /**
* Use this method to approve a chat join request. * Use this method to approve a chat join request.
* The command must be an <u>administrator</u> in the chat for this to work and must have the {@link ChatAdministratorRights#canInviteUsers()} administrator right. * The command must be an <u>administrator</u> in the chat for this to work and must have the {@link ChatAdministratorRights#canInviteUsers()} administrator right.
* Returns True on success. * Returns {@code true} on success.
* @param chatId Unique username of the target channel in the format @channelusername * @param chatId Unique username of the target channel in the format @channelusername
* @param userId Unique identifier of the target user * @param userId Unique identifier of the target user
* @see ChatAdministratorRights * @see ChatAdministratorRights
@@ -17,6 +17,7 @@ import hdvtdev.telegram.core.objects.User;
* @since 0.1.0 * @since 0.1.0
*/ */
//TODO NotTested //TODO NotTested
public record ApproveChatJoinRequest(String chatId, long userId) implements TelegramApiMethod<Boolean> { public record ApproveChatJoinRequest(String chatId, long userId) implements TelegramApiMethod<Boolean> {
/** /**

View File

@@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import hdvtdev.telegram.core.annotaions.Jsonable;
import hdvtdev.telegram.core.methods.util.ParseMode; import hdvtdev.telegram.core.methods.util.ParseMode;
import hdvtdev.telegram.core.objects.message.MessageEntity; import hdvtdev.telegram.core.objects.message.MessageEntity;
import hdvtdev.telegram.core.objects.poll.Poll; import hdvtdev.telegram.core.objects.poll.Poll;
@@ -24,7 +23,6 @@ import java.util.List;
* @since 1.0.0 * @since 1.0.0
*/ */
//TODO NotTested //TODO NotTested
@Jsonable
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public final class CopyMessage implements TelegramApiMethod<Long> { public final class CopyMessage implements TelegramApiMethod<Long> {
@@ -136,6 +134,12 @@ public final class CopyMessage implements TelegramApiMethod<Long> {
this.replyMarkup = replyMarkup; this.replyMarkup = replyMarkup;
} }
@JsonIgnore
@Override
public boolean isJsonable() {
return true;
}
@JsonIgnore @JsonIgnore
@Override @Override
public TelegramApiMethodBody getBody() { public TelegramApiMethodBody getBody() {

View File

@@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import hdvtdev.telegram.core.annotaions.Jsonable;
import hdvtdev.telegram.core.objects.poll.Poll; import hdvtdev.telegram.core.objects.poll.Poll;
import java.util.ArrayList; import java.util.ArrayList;
@@ -21,7 +20,7 @@ import java.util.List;
* @see Poll#correctOptionId() * @see Poll#correctOptionId()
* @since 1.0.0 * @since 1.0.0
*/ */
@Jsonable
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public final class CopyMessages implements TelegramApiMethod<Long[]> { public final class CopyMessages implements TelegramApiMethod<Long[]> {
@@ -124,6 +123,12 @@ public final class CopyMessages implements TelegramApiMethod<Long[]> {
return Long[].class; return Long[].class;
} }
@JsonIgnore
@Override
public boolean isJsonable() {
return true;
}
public static final class Builder { public static final class Builder {
private final String chatId; private final String chatId;
private Long messageThreadId; private Long messageThreadId;

View File

@@ -4,16 +4,14 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import hdvtdev.telegram.core.annotaions.Jsonable;
import hdvtdev.telegram.core.objects.message.Message; import hdvtdev.telegram.core.objects.message.Message;
/** /**
* Use this method to forward message of any kind. * Use this method to forward message of any kind.
* Service message and message with protected content can't be forwarded. * Service message and message with protected content can't be forwarded.
* On success, the sent {@link Message} is returned. * On success, the sent {@link Message} is returned.
*/ */
@Jsonable
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public final class ForwardMessage implements TelegramApiMethod<Message> { public final class ForwardMessage implements TelegramApiMethod<Message> {
@@ -90,6 +88,12 @@ public final class ForwardMessage implements TelegramApiMethod<Message> {
return Message.class; return Message.class;
} }
@JsonIgnore
@Override
public boolean isJsonable() {
return true;
}
public static final class Builder { public static final class Builder {
private final String chatId; private final String chatId;
private Long messageThreadId; private Long messageThreadId;

View File

@@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import hdvtdev.telegram.core.annotaions.Jsonable;
import hdvtdev.telegram.core.objects.message.Message; import hdvtdev.telegram.core.objects.message.Message;
import java.util.ArrayList; import java.util.ArrayList;
@@ -17,7 +16,6 @@ import java.util.List;
* @see Message#hasProtectedContent() * @see Message#hasProtectedContent()
*/ */
// TODO NotTested // TODO NotTested
@Jsonable
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public final class ForwardMessages implements TelegramApiMethod<Long[]> { public final class ForwardMessages implements TelegramApiMethod<Long[]> {
@@ -93,6 +91,11 @@ public final class ForwardMessages implements TelegramApiMethod<Long[]> {
return Long[].class; return Long[].class;
} }
@JsonIgnore
@Override
public boolean isJsonable() {
return true;
}
public static final class Builder { public static final class Builder {
private final String chatId; private final String chatId;

View File

@@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import hdvtdev.telegram.core.annotaions.Jsonable;
import hdvtdev.telegram.core.objects.command.BotCommand; import hdvtdev.telegram.core.objects.command.BotCommand;
import hdvtdev.telegram.core.objects.command.BotCommandScope; import hdvtdev.telegram.core.objects.command.BotCommandScope;
import hdvtdev.telegram.core.objects.command.BotCommandScopeDefault; import hdvtdev.telegram.core.objects.command.BotCommandScopeDefault;
@@ -17,7 +16,6 @@ import hdvtdev.telegram.core.objects.command.BotCommandScopeDefault;
* @see BotCommandScope * @see BotCommandScope
* @since 1.0.0 * @since 1.0.0
*/ */
@Jsonable
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public record GetMyCommands( public record GetMyCommands(
@JsonProperty("scope") BotCommandScope scope, @JsonProperty("scope") BotCommandScope scope,
@@ -53,4 +51,10 @@ public record GetMyCommands(
public Class<BotCommand[]> getResponseClass() { public Class<BotCommand[]> getResponseClass() {
return BotCommand[].class; return BotCommand[].class;
} }
@JsonIgnore
@Override
public boolean isJsonable() {
return true;
}
} }

View File

@@ -1,5 +1,7 @@
package hdvtdev.telegram.core.methods; package hdvtdev.telegram.core.methods;
import org.jetbrains.annotations.NotNull;
public record GetMyName(String languageCode) implements TelegramApiMethod<GetMyName.BotName> { public record GetMyName(String languageCode) implements TelegramApiMethod<GetMyName.BotName> {
public GetMyName() { public GetMyName() {
@@ -30,7 +32,7 @@ public record GetMyName(String languageCode) implements TelegramApiMethod<GetMyN
public record BotName(String name) { public record BotName(String name) {
@Override @Override
public String toString() { public @NotNull String toString() {
return this.name; return this.name;
} }

View File

@@ -4,12 +4,10 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import hdvtdev.telegram.core.annotaions.Jsonable;
import hdvtdev.telegram.core.objects.message.Message; import hdvtdev.telegram.core.objects.message.Message;
import hdvtdev.telegram.core.objects.markup.ReplyMarkup; import hdvtdev.telegram.core.objects.markup.ReplyMarkup;
import hdvtdev.telegram.core.objects.ReplyParameters; import hdvtdev.telegram.core.objects.ReplyParameters;
@Jsonable
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public final class SendDice implements TelegramApiMethod<Message> { public final class SendDice implements TelegramApiMethod<Message> {
@@ -106,6 +104,12 @@ public final class SendDice implements TelegramApiMethod<Message> {
return Message.class; return Message.class;
} }
@JsonIgnore
@Override
public boolean isJsonable() {
return true;
}
public enum Emoji { public enum Emoji {
DICE("🎲"), DICE("🎲"),
DART("🎯"), DART("🎯"),

View File

@@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import hdvtdev.telegram.core.annotaions.Jsonable;
import hdvtdev.telegram.core.methods.util.ParseMode; import hdvtdev.telegram.core.methods.util.ParseMode;
import hdvtdev.telegram.core.objects.*; import hdvtdev.telegram.core.objects.*;
import hdvtdev.telegram.core.objects.markup.ReplyMarkup; import hdvtdev.telegram.core.objects.markup.ReplyMarkup;
@@ -13,7 +12,6 @@ import hdvtdev.telegram.core.objects.message.Message;
import hdvtdev.telegram.core.objects.message.MessageEntity; import hdvtdev.telegram.core.objects.message.MessageEntity;
@Jsonable
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public final class SendMessage implements TelegramApiMethod<Message> { public final class SendMessage implements TelegramApiMethod<Message> {
@@ -137,6 +135,12 @@ public final class SendMessage implements TelegramApiMethod<Message> {
return Message.class; return Message.class;
} }
@JsonIgnore
@Override
public boolean isJsonable() {
return true;
}
public static final class Builder { public static final class Builder {
private final String chatId; private final String chatId;
private final String text; private final String text;

View File

@@ -4,12 +4,10 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import hdvtdev.telegram.core.annotaions.Jsonable;
import hdvtdev.telegram.core.objects.reaction.ReactionType; import hdvtdev.telegram.core.objects.reaction.ReactionType;
import java.util.List; import java.util.List;
@Jsonable
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public class SetMessageReaction implements TelegramApiMethod<Boolean> { public class SetMessageReaction implements TelegramApiMethod<Boolean> {
@@ -65,6 +63,12 @@ public class SetMessageReaction implements TelegramApiMethod<Boolean> {
return Boolean.class; return Boolean.class;
} }
@JsonIgnore
@Override
public boolean isJsonable() {
return true;
}
public static final class Builder { public static final class Builder {
private final String chatId; private final String chatId;
private final long messageId; private final long messageId;

View File

@@ -4,13 +4,11 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import hdvtdev.telegram.core.annotaions.Jsonable;
import hdvtdev.telegram.core.objects.command.BotCommand; import hdvtdev.telegram.core.objects.command.BotCommand;
import hdvtdev.telegram.core.objects.command.BotCommandScope; import hdvtdev.telegram.core.objects.command.BotCommandScope;
import java.util.List; import java.util.List;
@Jsonable
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public final class SetMyCommands implements TelegramApiMethod<Boolean> { public final class SetMyCommands implements TelegramApiMethod<Boolean> {
@@ -68,6 +66,12 @@ public final class SetMyCommands implements TelegramApiMethod<Boolean> {
return Boolean.class; return Boolean.class;
} }
@JsonIgnore
@Override
public boolean isJsonable() {
return true;
}
public static final class Builder { public static final class Builder {
private final List<BotCommand> commands; private final List<BotCommand> commands;

View File

@@ -8,4 +8,8 @@ public interface TelegramApiMethod<T> {
Class<T> getResponseClass(); Class<T> getResponseClass();
default boolean isJsonable() {
return false;
}
} }

View File

@@ -1,7 +1,6 @@
package hdvtdev.telegram.core.methods; package hdvtdev.telegram.core.methods;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.function.Consumer;
public final class TelegramApiMethodBody { public final class TelegramApiMethodBody {

View File

@@ -3,6 +3,7 @@ package hdvtdev.telegram.core.objects;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import hdvtdev.telegram.core.objects.business.BusinessConnection; import hdvtdev.telegram.core.objects.business.BusinessConnection;
import hdvtdev.telegram.core.objects.business.BusinessMessagesDeleted; import hdvtdev.telegram.core.objects.business.BusinessMessagesDeleted;
import hdvtdev.telegram.core.objects.callback.CallbackQuery; import hdvtdev.telegram.core.objects.callback.CallbackQuery;
@@ -19,6 +20,9 @@ import hdvtdev.telegram.core.objects.payment.ShippingQuery;
import hdvtdev.telegram.core.objects.poll.Poll; import hdvtdev.telegram.core.objects.poll.Poll;
import hdvtdev.telegram.core.objects.poll.PollAnswer; import hdvtdev.telegram.core.objects.poll.PollAnswer;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import java.util.Optional; import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
@@ -48,8 +52,15 @@ public record Update(
@JsonProperty("chat_join_request") ChatJoinRequest chatJoinRequest, @JsonProperty("chat_join_request") ChatJoinRequest chatJoinRequest,
@JsonProperty("chat_boost") ChatBoostUpdated chatBoost, @JsonProperty("chat_boost") ChatBoostUpdated chatBoost,
@JsonProperty("removed_chat_boost") ChatBoostRemoved chatBoostRemoved @JsonProperty("removed_chat_boost") ChatBoostRemoved chatBoostRemoved
) { ) implements GeneralObject {
@Override
@Nullable
public Message message() {
return message;
}
@Contract(pure = true)
public boolean hasMessage() { public boolean hasMessage() {
return this.message != null; return this.message != null;
} }

View File

@@ -3,6 +3,7 @@ package hdvtdev.telegram.core.objects.callback;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import hdvtdev.telegram.core.objects.GeneralObject;
import hdvtdev.telegram.core.objects.User; import hdvtdev.telegram.core.objects.User;
import hdvtdev.telegram.core.objects.message.MaybeInaccessibleMessage; import hdvtdev.telegram.core.objects.message.MaybeInaccessibleMessage;
@@ -16,7 +17,7 @@ public record CallbackQuery(
@JsonProperty("chat_instance") String chatInstance, @JsonProperty("chat_instance") String chatInstance,
@JsonProperty("data") String data, @JsonProperty("data") String data,
@JsonProperty("game_short_name") String gameShortName @JsonProperty("game_short_name") String gameShortName
) { ) implements GeneralObject {
public boolean hasMessage() { public boolean hasMessage() {
return this.message != null; return this.message != null;

View File

@@ -113,7 +113,7 @@ public record Message(
@JsonProperty("web_app_data") WebAppData webAppData, @JsonProperty("web_app_data") WebAppData webAppData,
@JsonProperty("reply_markup") InlineKeyboardMarkup inlineKeyboardMarkup @JsonProperty("reply_markup") InlineKeyboardMarkup inlineKeyboardMarkup
) implements MaybeInaccessibleMessage { ) implements MaybeInaccessibleMessage, GeneralObject {
public boolean hasMessageThreadId() { public boolean hasMessageThreadId() {
return messageThreadId != null; return messageThreadId != null;

234
gradlew vendored
View File

@@ -1,234 +0,0 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
gradlew.bat vendored
View File

@@ -1,89 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -1,6 +0,0 @@
module longpolling.okhttp {
exports hdvtdev.telegram.longpolling.okhttp;
requires core;
requires okhttp3;
requires com.fasterxml.jackson.databind;
}