4 Commits

Author SHA1 Message Date
87de3ff874 [maven-release-plugin] prepare release 0.0.2 2026-03-03 13:28:00 +03:00
c43ba2ea8b Update PengradTelegramBot to improve chat ID retrieval and upgrade Telegram API version
- Refactor chat ID extraction logic into a separate method for clarity and maintainability.
- Handle cases where chat ID may not be accessible, logging a warning when not found.
- Upgrade Telegram Bot API dependency version from 6.2.0 to 7.1.1.
- Adjust BotRequestImpl to accommodate changes in chat ID retrieval logic.
- Make botAtomicReference in App class final for better thread safety.
2026-03-03 13:26:14 +03:00
a06f9940ff #3 change sessions impl 2022-09-25 09:33:42 +03:00
8453ba42f8 up java-telegram-bot-api version 2022-09-24 14:15:22 +03:00
17 changed files with 340 additions and 207 deletions

43
pom.xml
View File

@@ -6,7 +6,7 @@
<groupId>ru.penkrat.stbf</groupId>
<artifactId>stbf-parent</artifactId>
<version>0.0.2-SNAPSHOT</version>
<version>0.0.2</version>
<name>stbf-parent</name>
<description>Simple Telegram Bot Facade</description>
@@ -14,8 +14,8 @@
<scm>
<connection>scm:git:https://git.penkrat.ru/ruslan/stbf.git</connection>
<developerConnection>scm:git:https://git.penkrat.ru/ruslan/stbf.git</developerConnection>
<tag>HEAD</tag>
</scm>
<tag>0.0.2</tag>
</scm>
<licenses>
<license>
@@ -65,6 +65,43 @@
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<phase>deploy</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<executions>
<execution>
<id>attach-javadocs</id>
<phase>deploy</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<!-- explicitly define maven-deploy-plugin after other to force exec order -->
<artifactId>maven-deploy-plugin</artifactId>
<executions>
<execution>
<id>deploy</id>
<phase>deploy</phase>
<goals>
<goal>deploy</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>

View File

@@ -5,7 +5,7 @@
<parent>
<groupId>ru.penkrat.stbf</groupId>
<artifactId>stbf-parent</artifactId>
<version>0.0.2-SNAPSHOT</version>
<version>0.0.2</version>
</parent>
<artifactId>stbf-api</artifactId>

View File

@@ -4,7 +4,7 @@
<parent>
<artifactId>stbf-parent</artifactId>
<groupId>ru.penkrat.stbf</groupId>
<version>0.0.2-SNAPSHOT</version>
<version>0.0.2</version>
</parent>
<artifactId>stbf-common</artifactId>
@@ -14,7 +14,7 @@
<dependency>
<groupId>ru.penkrat.stbf</groupId>
<artifactId>stbf-api</artifactId>
<version>0.0.2-SNAPSHOT</version>
<version>0.0.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>

View File

@@ -0,0 +1,20 @@
package ru.penkrat.stbf.common.command;
import lombok.RequiredArgsConstructor;
import ru.penkrat.stbf.api.BotRequest;
import ru.penkrat.stbf.api.BotResponse;
import ru.penkrat.stbf.api.CommandChain;
import ru.penkrat.stbf.api.SessionProvider;
import ru.penkrat.stbf.common.session.SessionAwareBotRequest;
@RequiredArgsConstructor
public class SessionAwareCommandChain implements CommandChain {
private final CommandChain delegate;
private final SessionProvider sessionProvider;
@Override
public void processCommand(BotRequest botRequest, BotResponse botResponse) {
delegate.processCommand(new SessionAwareBotRequest(botRequest, sessionProvider), botResponse);
}
}

View File

@@ -0,0 +1,31 @@
package ru.penkrat.stbf.common.command;
import ru.penkrat.stbf.api.BotRequest;
import ru.penkrat.stbf.api.BotResponse;
import ru.penkrat.stbf.api.CommandChain;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPolledCommandChain implements CommandChain {
private final CommandChain delegate;
private final ExecutorService executor;
public ThreadPolledCommandChain(CommandChain delegate) {
this(delegate, 4);
}
public ThreadPolledCommandChain(CommandChain delegate, int nThreads) {
this.delegate = delegate;
this.executor = Executors.newFixedThreadPool(nThreads);
}
@Override
public void processCommand(BotRequest botRequest, BotResponse botResponse) {
executor.execute(() -> {
delegate.processCommand(botRequest, botResponse);
});
}
}

View File

@@ -0,0 +1,49 @@
package ru.penkrat.stbf.common.session;
import lombok.RequiredArgsConstructor;
import ru.penkrat.stbf.api.BotRequest;
import ru.penkrat.stbf.api.BotSession;
import ru.penkrat.stbf.api.SessionProvider;
import java.util.Objects;
import java.util.Optional;
@RequiredArgsConstructor
public class SessionAwareBotRequest implements BotRequest {
private final BotRequest delegate;
private final SessionProvider sessionProvider;
private BotSession botSession;
@Override
public BotSession getSession() {
if (botSession == null) {
botSession = sessionProvider.get(getChatId());
Objects.requireNonNull(botSession, "Session can not be null");
}
return botSession;
}
public Optional<String> getMessageText() {
return this.delegate.getMessageText();
}
public Optional<String> getPhoneNumber() {
return this.delegate.getPhoneNumber();
}
public Optional<String> getCallbackData() {
return this.delegate.getCallbackData();
}
public Optional<String> getCallbackMessageText() {
return this.delegate.getCallbackMessageText();
}
public Long getChatId() {
return this.delegate.getChatId();
}
}

View File

@@ -4,7 +4,7 @@
<parent>
<artifactId>stbf-parent</artifactId>
<groupId>ru.penkrat.stbf</groupId>
<version>0.0.2-SNAPSHOT</version>
<version>0.0.2</version>
</parent>
<groupId>ru.penkrat.stbf</groupId>

View File

@@ -5,6 +5,8 @@ import org.slf4j.LoggerFactory;
import picocli.CommandLine;
import ru.penkrat.stbf.api.BotCommandChain;
import ru.penkrat.stbf.api.CommandChain;
import ru.penkrat.stbf.common.command.SessionAwareCommandChain;
import ru.penkrat.stbf.common.command.ThreadPolledCommandChain;
import ru.penkrat.stbf.common.session.InMemBotSessionProvider;
import ru.penkrat.stbf.impl.pengrad.PengradTelegramBot;
import ru.penkrat.stbf.templates.xml.XmlFlowResolver;
@@ -12,58 +14,58 @@ import ru.penkrat.stbf.templates.xml.XmlFlowResolver;
import java.util.concurrent.atomic.AtomicReference;
@CommandLine.Command(name = "java -jar stbf-demo.jar", mixinStandardHelpOptions = true, description = "Run bot",
version = "Simple Telegram bot framework Demo app v. 0.0.1")
version = "Simple Telegram bot framework Demo app v. 0.0.2")
public class App implements Runnable {
private static final Logger log = LoggerFactory.getLogger(App.class);
private static final Logger log = LoggerFactory.getLogger(App.class);
private static AtomicReference<PengradTelegramBot> botAtomicReference = new AtomicReference<>();
private static final AtomicReference<PengradTelegramBot> botAtomicReference = new AtomicReference<>();
@CommandLine.Option(names = {"-f", "--file"}, description = "The file with config.")
private String flowFile = "classpath:/flow.xml";
@CommandLine.Option(names = {"-f", "--file"}, description = "The file with config.")
private String flowFile = "classpath:/flow.xml";
@CommandLine.Option(names = {"-t", "--token"}, required = true, description = "bot token 1234:abscdf...")
private String botToken = "";
@CommandLine.Option(names = {"-t", "--token"}, required = true, description = "bot token 1234:abscdf...")
private String botToken = "";
public static void main(String[] args) {
new CommandLine(new App()).execute(args);
}
public static void main(String[] args) {
new CommandLine(new App()).execute(args);
}
private BotCommandChain getCommandChain(String filename) {
XmlFlowResolver flow = new XmlFlowResolver(filename);
private CommandChain getCommandChain(String filename) {
XmlFlowResolver flow = new XmlFlowResolver(filename);
BotCommandChain chain = new BotCommandChain();
flow.getCommands().forEach(chain::add);
BotCommandChain chain = new BotCommandChain();
flow.getCommands().forEach(chain::add);
return chain;
}
return new ThreadPolledCommandChain(new SessionAwareCommandChain(chain, new InMemBotSessionProvider()));
}
private Runnable start(String token, CommandChain chain) {
return () -> botAtomicReference.set(new PengradTelegramBot(token, chain, new InMemBotSessionProvider()));
}
private Runnable start(String token, CommandChain chain) {
return () -> botAtomicReference.set(new PengradTelegramBot(token, chain));
}
private void onShutdown() {
try {
if (botAtomicReference.get() != null) {
botAtomicReference.get().close();
log.info("Bot finished.");
}
} catch (Exception e) {
log.error("Error:", e);
}
}
private void onShutdown() {
try {
if (botAtomicReference.get() != null) {
botAtomicReference.get().close();
log.info("Bot finished.");
}
} catch (Exception e) {
log.error("Error:", e);
}
}
@Override
public void run() {
Thread botThread = new Thread(start(botToken, getCommandChain(flowFile)));
botThread.setDaemon(false);
botThread.setName("stbf-bot-thread");
@Override
public void run() {
Thread botThread = new Thread(start(botToken, getCommandChain(flowFile)));
botThread.setDaemon(false);
botThread.setName("stbf-bot-thread");
Runtime.getRuntime().addShutdownHook(new Thread(this::onShutdown));
Runtime.getRuntime().addShutdownHook(new Thread(this::onShutdown));
log.info("Starting bot...");
botThread.start();
log.info("Bot started.");
log.info("Press Ctrl+C to exit.");
}
log.info("Starting bot...");
botThread.start();
log.info("Bot started.");
log.info("Press Ctrl+C to exit.");
}
}

View File

@@ -5,7 +5,7 @@
<parent>
<groupId>ru.penkrat.stbf</groupId>
<artifactId>stbf-parent</artifactId>
<version>0.0.2-SNAPSHOT</version>
<version>0.0.2</version>
</parent>
<artifactId>stbf-pengrad</artifactId>
@@ -16,12 +16,12 @@
<dependency>
<groupId>ru.penkrat.stbf</groupId>
<artifactId>stbf-api</artifactId>
<version>0.0.2-SNAPSHOT</version>
<version>0.0.2</version>
</dependency>
<dependency>
<groupId>com.github.pengrad</groupId>
<artifactId>java-telegram-bot-api</artifactId>
<version>[4.9.0,5.2.0]</version>
<version>7.1.1</version>
</dependency>
</dependencies>

View File

@@ -16,49 +16,49 @@ import static lombok.AccessLevel.PROTECTED;
@RequiredArgsConstructor
public class BotRequestImpl implements BotRequest {
@Getter(PROTECTED)
private final Update update;
@Getter(PROTECTED)
private final Update update;
@Getter
private final BotSession session;
@Override
public Optional<String> getMessageText() {
if (update.message() != null) {
return Optional.ofNullable(update.message().text());
}
return Optional.empty();
}
@Override
public Optional<String> getMessageText() {
if (update.message() != null) {
return Optional.ofNullable(update.message().text());
}
return Optional.empty();
}
@Override
public Optional<String> getPhoneNumber() {
return Optional.of(update)
.map(Update::message)
.map(Message::contact)
.map(Contact::phoneNumber);
}
@Override
public Optional<String> getPhoneNumber() {
return Optional.of(update)
.map(Update::message)
.map(Message::contact)
.map(Contact::phoneNumber);
}
@Override
public Optional<String> getCallbackData() {
return Optional.of(update)
.map(Update::callbackQuery)
.map(CallbackQuery::data);
}
@Override
public Optional<String> getCallbackData() {
return Optional.of(update)
.map(Update::callbackQuery)
.map(CallbackQuery::data);
}
@Override
public Optional<String> getCallbackMessageText() {
// unsupported ? todo: check doc
return Optional.empty();
}
@Override
public Optional<String> getCallbackMessageText() {
return Optional.of(update)
.map(Update::callbackQuery)
.map(CallbackQuery::message)
.map(Message::text);
}
@Override
public Long getChatId() {
return Optional.of(update)
.map(Update::callbackQuery)
.map(CallbackQuery::maybeInaccessibleMessage)
.orElseGet(update::message).chat().id();
}
@Override
public Long getChatId() {
return Optional.of(update)
.map(Update::callbackQuery)
.map(CallbackQuery::message)
.orElseGet(() -> update.message()).chat().id();
}
@Override
public BotSession getSession() {
throw new UnsupportedOperationException("Session is not supported");
}
}

View File

@@ -1,6 +1,6 @@
package ru.penkrat.stbf.impl.pengrad;
import com.google.gson.internal.reflect.ReflectionAccessor;
import com.google.gson.internal.reflect.ReflectionHelper;
import com.pengrad.telegrambot.model.request.InlineKeyboardButton;
import com.pengrad.telegrambot.model.request.KeyboardButton;
import lombok.Value;
@@ -58,7 +58,7 @@ class KeyboardImpl implements Keyboard {
return text.computeIfAbsent(btn, o -> {
try {
Field text = btn.getClass().getDeclaredField("text");
ReflectionAccessor.getInstance().makeAccessible(text);
ReflectionHelper.makeAccessible(text);
return String.valueOf(text.get(btn));
} catch (NoSuchFieldException | IllegalAccessException e) {
return "*error*";

View File

@@ -2,50 +2,51 @@ package ru.penkrat.stbf.impl.pengrad;
import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.UpdatesListener;
import com.pengrad.telegrambot.model.CallbackQuery;
import com.pengrad.telegrambot.model.Update;
import lombok.extern.slf4j.Slf4j;
import ru.penkrat.stbf.api.CommandChain;
import ru.penkrat.stbf.api.SessionProvider;
import java.util.Optional;
@Slf4j
public class PengradTelegramBot extends TelegramBot implements AutoCloseable {
public PengradTelegramBot(String botToken, CommandChain commandChain) {
this(botToken, commandChain, (id) -> {
throw new IllegalArgumentException("'SessionProvider' is not defined");
});
}
public PengradTelegramBot(String botToken, CommandChain commandChain) {
super(botToken);
this.setUpdatesListener(updates -> {
for (Update update : updates) {
try {
final Long chatId = findChatId(update);
if (chatId == null) {
log.warn("Chat not found, Update [id={}]", update.updateId());
continue;
}
log.debug("New message in chat {}", chatId);
public PengradTelegramBot(String botToken, CommandChain commandChain, SessionProvider sessionProvider) {
super(botToken);
this.setUpdatesListener(updates -> {
for (Update update : updates) {
try {
final Long chatId = Optional.of(update)
.map(Update::callbackQuery)
.map(CallbackQuery::message)
.orElseGet(() -> update.message()).chat().id();
commandChain.processCommand(
new BotRequestImpl(update),
new BotResponseImpl(update, this));
} catch (Exception e) {
log.error("Bot Error:", e);
}
}
return UpdatesListener.CONFIRMED_UPDATES_ALL;
});
}
log.debug("New message in chat {}", chatId);
@Override
public void close() throws Exception {
removeGetUpdatesListener();
log.debug("Bot closed.");
}
commandChain.processCommand(
new BotRequestImpl(update, sessionProvider.get(chatId)),
new BotResponseImpl(update, this));
} catch (Exception e) {
log.error("Bot Error:", e);
}
}
return UpdatesListener.CONFIRMED_UPDATES_ALL;
});
}
private Long findChatId(Update update) {
if (update.callbackQuery() != null && update.callbackQuery().maybeInaccessibleMessage() != null) {
return update.callbackQuery().maybeInaccessibleMessage().chat().id();
}
if (update.message() != null) {
return update.message().chat().id();
}
@Override
public void close() throws Exception {
removeGetUpdatesListener();
log.debug("Bot closed.");
}
return null;
}
}

View File

@@ -4,7 +4,7 @@
<parent>
<artifactId>stbf-parent</artifactId>
<groupId>ru.penkrat.stbf</groupId>
<version>0.0.2-SNAPSHOT</version>
<version>0.0.2</version>
</parent>
<artifactId>stbf-rubenlagus</artifactId>
@@ -15,7 +15,7 @@
<dependency>
<groupId>ru.penkrat.stbf</groupId>
<artifactId>stbf-api</artifactId>
<version>0.0.2-SNAPSHOT</version>
<version>0.0.2</version>
</dependency>
<dependency>
<groupId>org.telegram</groupId>

View File

@@ -16,46 +16,48 @@ import static lombok.AccessLevel.PROTECTED;
@RequiredArgsConstructor
class BotRequestImpl implements BotRequest {
@Getter(PROTECTED)
private final Update update;
@Getter(PROTECTED)
private final Update update;
@Getter
private final BotSession session;
@Override
public Optional<String> getMessageText() {
if (update.hasMessage()) {
return Optional.ofNullable(update.getMessage().getText());
}
return Optional.empty();
}
@Override
public Optional<String> getMessageText() {
if (update.hasMessage()) {
return Optional.ofNullable(update.getMessage().getText());
}
return Optional.empty();
}
@Override
public Optional<String> getPhoneNumber() {
return Optional.of(update)
.map(Update::getMessage)
.map(Message::getContact)
.map(Contact::getPhoneNumber);
}
@Override
public Optional<String> getPhoneNumber() {
return Optional.of(update)
.map(Update::getMessage)
.map(Message::getContact)
.map(Contact::getPhoneNumber);
}
@Override
public Optional<String> getCallbackData() {
return Optional.of(update)
.map(Update::getCallbackQuery)
.map(CallbackQuery::getData);
}
@Override
public Optional<String> getCallbackData() {
return Optional.of(update)
.map(Update::getCallbackQuery)
.map(CallbackQuery::getData);
}
@Override
public Optional<String> getCallbackMessageText() {
return Optional.of(update)
.map(Update::getCallbackQuery)
.map(CallbackQuery::getMessage)
.map(Message::getText);
}
@Override
public Optional<String> getCallbackMessageText() {
return Optional.of(update)
.map(Update::getCallbackQuery)
.map(CallbackQuery::getMessage)
.map(Message::getText);
}
@Override
public Long getChatId() {
return Utils.getChatId(update);
}
@Override
public Long getChatId() {
return Utils.getChatId(update);
}
@Override
public BotSession getSession() {
throw new UnsupportedOperationException("Session is not supported");
}
}

View File

@@ -7,56 +7,47 @@ import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;
import ru.penkrat.stbf.api.BotCommandChain;
import ru.penkrat.stbf.api.SessionProvider;
@Slf4j
public class RubenlagusTelegramBot extends TelegramLongPollingBot {
private final String botUsername;
private final String botToken;
private final BotCommandChain commandChain;
private final SessionProvider sessionProvider;
private final String botUsername;
private final String botToken;
private final BotCommandChain commandChain;
public RubenlagusTelegramBot(String botUsername, String botToken, BotCommandChain botCommandChain) {
this(botUsername, botToken, botCommandChain, (id) -> {
throw new IllegalArgumentException("'SessionProvider' is not defined");
});
}
public RubenlagusTelegramBot(String botUsername, String botToken, BotCommandChain botCommandChain) {
this.botUsername = botUsername;
this.botToken = botToken;
this.commandChain = botCommandChain;
public RubenlagusTelegramBot(String botUsername, String botToken, BotCommandChain botCommandChain, SessionProvider sessionProvider) {
this.botUsername = botUsername;
this.botToken = botToken;
this.commandChain = botCommandChain;
this.sessionProvider = sessionProvider;
TelegramBotsApi telegramBotsApi;
try {
telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class);
telegramBotsApi.registerBot(this);
} catch (TelegramApiException e) {
log.error("Error", e);
}
}
TelegramBotsApi telegramBotsApi;
try {
telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class);
telegramBotsApi.registerBot(this);
} catch (TelegramApiException e) {
log.error("Error", e);
}
}
@Override
public void onUpdateReceived(Update update) {
try {
commandChain.processCommand(
new BotRequestImpl(update),
new BotResponseImpl(update, this));
} catch (Exception e) {
log.error("Bot Error:", e);
}
}
@Override
public void onUpdateReceived(Update update) {
try {
commandChain.processCommand(
new BotRequestImpl(update, sessionProvider.get(Utils.getChatId(update))),
new BotResponseImpl(update, this));
} catch (Exception e) {
log.error("Bot Error:", e);
}
}
@Override
public String getBotUsername() {
return botUsername;
}
@Override
public String getBotUsername() {
return botUsername;
}
@Override
public String getBotToken() {
return botToken;
}
@Override
public String getBotToken() {
return botToken;
}
}

View File

@@ -4,7 +4,7 @@
<parent>
<artifactId>stbf-parent</artifactId>
<groupId>ru.penkrat.stbf</groupId>
<version>0.0.2-SNAPSHOT</version>
<version>0.0.2</version>
</parent>
<artifactId>stbf-templates</artifactId>
<properties>

View File

@@ -4,7 +4,7 @@
<parent>
<artifactId>stbf-parent</artifactId>
<groupId>ru.penkrat.stbf</groupId>
<version>0.0.2-SNAPSHOT</version>
<version>0.0.2</version>
</parent>
<artifactId>stbf-test</artifactId>
@@ -14,12 +14,12 @@
<dependency>
<groupId>ru.penkrat.stbf</groupId>
<artifactId>stbf-api</artifactId>
<version>0.0.2-SNAPSHOT</version>
<version>0.0.2</version>
</dependency>
<dependency>
<groupId>ru.penkrat.stbf</groupId>
<artifactId>stbf-common</artifactId>
<version>0.0.2-SNAPSHOT</version>
<version>0.0.2</version>
<scope>test</scope>
</dependency>
<dependency>