Compare commits
5 Commits
b8615d3b90
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a9742134b2 | ||
|
|
a8b772a5ea | ||
|
|
ca295b66f9 | ||
|
|
9fdfd91e1d | ||
|
|
7607ec4205 |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -41,3 +41,7 @@ bin/
|
|||||||
### Mac OS ###
|
### Mac OS ###
|
||||||
.DS_Store
|
.DS_Store
|
||||||
/core/src/main/java/hdvtdev/telegram/Count.java
|
/core/src/main/java/hdvtdev/telegram/Count.java
|
||||||
|
/src/
|
||||||
|
/test/
|
||||||
|
/.idea/
|
||||||
|
/gradle/
|
||||||
|
|||||||
4
.idea/gradle.xml
generated
4
.idea/gradle.xml
generated
@@ -8,8 +8,12 @@
|
|||||||
<option name="modules">
|
<option name="modules">
|
||||||
<set>
|
<set>
|
||||||
<option value="$PROJECT_DIR$" />
|
<option value="$PROJECT_DIR$" />
|
||||||
|
<option value="$PROJECT_DIR$/annotation-processor" />
|
||||||
<option value="$PROJECT_DIR$/core" />
|
<option value="$PROJECT_DIR$/core" />
|
||||||
|
<option value="$PROJECT_DIR$/event-handlers" />
|
||||||
|
<option value="$PROJECT_DIR$/event-handlers-annotations" />
|
||||||
<option value="$PROJECT_DIR$/longpolling-okhttp" />
|
<option value="$PROJECT_DIR$/longpolling-okhttp" />
|
||||||
|
<option value="$PROJECT_DIR$/test" />
|
||||||
</set>
|
</set>
|
||||||
</option>
|
</option>
|
||||||
</GradleProjectSettings>
|
</GradleProjectSettings>
|
||||||
|
|||||||
1
.idea/misc.xml
generated
1
.idea/misc.xml
generated
@@ -1,4 +1,3 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
<project version="4">
|
||||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||||
<component name="FrameworkDetectionExcludesConfiguration">
|
<component name="FrameworkDetectionExcludesConfiguration">
|
||||||
|
|||||||
141
README.md
141
README.md
@@ -1,10 +1,143 @@
|
|||||||
|
|
||||||
|
|
||||||
|
### English Version
|
||||||
|
|
||||||
|
# TeleJ
|
||||||
|
|
||||||
|
An elegant Java library for creating Telegram bots, featuring a framework module to reduce boilerplate and speed up development.
|
||||||
|
|
||||||
|
## ⚠️ Project Status ⚠️
|
||||||
|
|
||||||
|
**This project is currently under active development.** APIs may change, and features are still being added. It is not yet recommended for production use.
|
||||||
|
|
||||||
|
## About The Project
|
||||||
|
|
||||||
|
TeleJ is a library designed to simplify and accelerate the process of creating Telegram bots in Java. It provides a convenient API and a modular structure that helps you focus on your bot's logic rather than on repetitive code.
|
||||||
|
|
||||||
|
## Key Features
|
||||||
|
|
||||||
|
* **Simple Setup:** Get started with your bot quickly.
|
||||||
|
* **Modular Architecture:** Includes a `core` module, an `event-handlers` framework module, and other components that can be included as needed.
|
||||||
|
* **Modern Approach:** Utilizes modern Java features to create clean and readable code.
|
||||||
|
* **Extensible:** Easily extendable to add custom functionality.
|
||||||
|
|
||||||
|
|
||||||
|
### Usage Example
|
||||||
|
|
||||||
|
Below is a simple example of how to create and run a bot using TeleJ.
|
||||||
|
|
||||||
|
```java
|
||||||
|
public class MyAwesomeBot {
|
||||||
|
|
||||||
|
private static final TelegramBot telegramBot = new OkHttpTelegramBot("token");
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
|
||||||
|
telegramBot.start(new UpdateConsumer() {
|
||||||
|
@Override
|
||||||
|
public void onUpdate(Update update) {
|
||||||
|
|
||||||
|
if (update.hasMessage()) {
|
||||||
|
Message message = update.message();
|
||||||
|
if (message.hasText()) {
|
||||||
|
if (message.text().equalsIgnoreCase("ping!")) {
|
||||||
|
telegramBot.execute(new SendMessage.Builder(
|
||||||
|
message.chatId(), "pong!").replyToMessage(message.messageId())
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
The project consists of several modules:
|
||||||
|
|
||||||
|
* `core`: The core of the library with all the basic functions for interacting with the Telegram Bot API.
|
||||||
|
* `event-handlers`: A framework module designed to reduce boilerplate and speed up development by simplifying the handling of events and updates from Telegram.
|
||||||
|
* `annotation-processor`: An annotation processor to simplify code writing.
|
||||||
|
* `longpolling-okhttp`: An implementation for receiving updates via Long Polling using OkHttp.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
This project is distributed under the MIT License.
|
||||||
|
|
||||||
|
***
|
||||||
|
|
||||||
|
### Русская версия
|
||||||
|
|
||||||
|
# TeleJ
|
||||||
|
|
||||||
|
Изящная библиотека на Java для создания ботов в Telegram, с модулем фреймворка для ускорения разработки и уменьшения количества шаблонного кода.
|
||||||
|
|
||||||
|
## ⚠️ Статус проекта ⚠️
|
||||||
|
|
||||||
|
**Этот проект находится в стадии активной разработки.** API может изменяться, а новые функции все еще добавляются. Пока не рекомендуется использовать его в продакшене.
|
||||||
|
|
||||||
|
## О проекте
|
||||||
|
|
||||||
|
TeleJ — это библиотека, разработанная для упрощения и ускорения процесса создания ботов для Telegram на языке Java. Она предоставляет удобный API и модульную структуру, которая помогает сосредоточиться на логике вашего бота, а не на повторяющемся коде.
|
||||||
|
|
||||||
|
## Основные возможности
|
||||||
|
|
||||||
|
* **Простая настройка:** Быстрое начало работы с вашим ботом.
|
||||||
|
* **Модульная архитектура:** Включает основной модуль (`core`), модуль фреймворка (`event-handlers`) и другие компоненты, которые можно подключать по мере необходимости.
|
||||||
|
* **Современный подход:** Использует современные возможности Java для создания чистого и читаемого кода.
|
||||||
|
* **Расширяемость:** Легко расширяется для добавления пользовательского функционала.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### Пример использования
|
||||||
|
|
||||||
Total lines of code:
|
Ниже приведен простой пример того, как создать и запустить бота с использованием TeleJ.
|
||||||
|
|
||||||
|
```java
|
||||||
|
public class MyAwesomeBot {
|
||||||
|
|
||||||
|
private static final TelegramBot telegramBot = new OkHttpTelegramBot("token");
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
|
||||||
<p>
|
telegramBot.start(new UpdateConsumer() {
|
||||||
<span style="background-color: blue; color: white; padding: 2px 4px;">08 April 2025 22:07:16 code: 6094 docs: 173</span>
|
@Override
|
||||||
<p>
|
public void onUpdate(Update update) {
|
||||||
|
|
||||||
|
if (update.hasMessage()) {
|
||||||
|
Message message = update.message();
|
||||||
|
if (message.hasText()) {
|
||||||
|
if (message.text().equalsIgnoreCase("ping!")) {
|
||||||
|
telegramBot.execute(new SendMessage.Builder(
|
||||||
|
message.chatId(), "pong!").replyToMessage(message.messageId())
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Структура проекта
|
||||||
|
|
||||||
|
Проект состоит из нескольких модулей:
|
||||||
|
|
||||||
|
* `core`: Ядро библиотеки со всеми основными функциями для взаимодействия с Telegram Bot API.
|
||||||
|
* `event-handlers`: Модуль фреймворка, предназначенный для уменьшения бойлерплейта (шаблонного кода) и ускорения разработки за счет упрощения обработки событий и обновлений от Telegram.
|
||||||
|
* `annotation-processor`: Обработчик аннотаций для упрощения написания кода.
|
||||||
|
* `longpolling-okhttp`: Реализация получения обновлений через Long Polling с использованием OkHttp.
|
||||||
|
|
||||||
|
|
||||||
|
## Лицензия
|
||||||
|
|
||||||
|
Этот проект распространяется под лицензией MIT License.
|
||||||
@@ -4,11 +4,15 @@ import java.io.IOException;
|
|||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
public class HandlerWriter {
|
public class HandlerWriter {
|
||||||
|
|
||||||
public static void write(String body) throws IOException {
|
public static void write(String body) throws IOException {
|
||||||
|
|
||||||
|
Consumer<String> consumer = (String s) -> {};
|
||||||
|
|
||||||
String classFilePath = "models/Handlers.class"; // Путь к вашему файлу
|
String classFilePath = "models/Handlers.class"; // Путь к вашему файлу
|
||||||
Path path = Paths.get(classFilePath);
|
Path path = Paths.get(classFilePath);
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
package hdvtdev.telegram.core;
|
|
||||||
|
|
||||||
import java.lang.reflect.Method;
|
|
||||||
|
|
||||||
public record InvokeMethod(Method method, Class<?> parameterType) {
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
package hdvtdev.telegram.core;
|
|
||||||
|
|
||||||
import hdvtdev.telegram.core.objects.Update;
|
|
||||||
|
|
||||||
@FunctionalInterface
|
|
||||||
public interface UpdateExecutor {
|
|
||||||
|
|
||||||
void execute(Update update);
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -12,11 +12,9 @@ repositories {
|
|||||||
dependencies {
|
dependencies {
|
||||||
implementation platform('com.fasterxml.jackson:jackson-bom:2.18.3')
|
implementation platform('com.fasterxml.jackson:jackson-bom:2.18.3')
|
||||||
|
|
||||||
|
|
||||||
implementation 'com.fasterxml.jackson.core:jackson-core'
|
implementation 'com.fasterxml.jackson.core:jackson-core'
|
||||||
implementation 'com.fasterxml.jackson.core:jackson-databind'
|
implementation 'com.fasterxml.jackson.core:jackson-databind'
|
||||||
|
|
||||||
//implementation 'com.squareup.okhttp3:okhttp:4.12.0'
|
|
||||||
implementation 'com.squareup.okhttp3:okhttp:5.2.1'
|
implementation 'com.squareup.okhttp3:okhttp:5.2.1'
|
||||||
implementation(project(":core"))
|
implementation(project(":core"))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
|||||||
import hdvtdev.telegram.core.HandlersModule;
|
import hdvtdev.telegram.core.HandlersModule;
|
||||||
import hdvtdev.telegram.core.TelegramBot;
|
import hdvtdev.telegram.core.TelegramBot;
|
||||||
import hdvtdev.telegram.core.UpdateConsumer;
|
import hdvtdev.telegram.core.UpdateConsumer;
|
||||||
import hdvtdev.telegram.core.UpdateExecutor;
|
|
||||||
import hdvtdev.telegram.core.exceptions.TelegramApiException;
|
import hdvtdev.telegram.core.exceptions.TelegramApiException;
|
||||||
import hdvtdev.telegram.core.exceptions.TelegramApiNetworkException;
|
import hdvtdev.telegram.core.exceptions.TelegramApiNetworkException;
|
||||||
import hdvtdev.telegram.core.exceptions.TelegramMethodParsingException;
|
import hdvtdev.telegram.core.exceptions.TelegramMethodParsingException;
|
||||||
@@ -28,6 +27,7 @@ import java.nio.file.StandardCopyOption;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
import java.util.concurrent.atomic.AtomicLong;
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
|
||||||
public class OkHttpTelegramBot implements TelegramBot {
|
public class OkHttpTelegramBot implements TelegramBot {
|
||||||
@@ -38,7 +38,7 @@ public class OkHttpTelegramBot implements TelegramBot {
|
|||||||
|
|
||||||
private ScheduledExecutorService scheduler;
|
private ScheduledExecutorService scheduler;
|
||||||
|
|
||||||
private final UpdateExecutor updateExecutor;
|
private final Consumer<Update> updateExecutor;
|
||||||
private final AtomicLong lastUpdateId = new AtomicLong(0);
|
private final AtomicLong lastUpdateId = new AtomicLong(0);
|
||||||
private int updateLimit = 10;
|
private int updateLimit = 10;
|
||||||
private int updateTimeout = 25;
|
private int updateTimeout = 25;
|
||||||
@@ -153,7 +153,7 @@ public class OkHttpTelegramBot implements TelegramBot {
|
|||||||
List<Update> updates = List.of(awaitExecute(new GetUpdates(lastUpdateId.get() + 1, updateLimit, updateTimeout)));
|
List<Update> updates = List.of(awaitExecute(new GetUpdates(lastUpdateId.get() + 1, updateLimit, updateTimeout)));
|
||||||
if (!updates.isEmpty()) {
|
if (!updates.isEmpty()) {
|
||||||
for (Update update : updates) {
|
for (Update update : updates) {
|
||||||
updateExecutor.execute(update);
|
updateExecutor.accept(update);
|
||||||
}
|
}
|
||||||
lastUpdateId.set(updates.getLast().updateId());
|
lastUpdateId.set(updates.getLast().updateId());
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user