Simple BotThread Telegram

Iniciado por Swarlog, Jun 25, 2025, 09:06 PM

Tema anterior - Siguiente tema

Swarlog

Un pequeño ejemplo de manejo de actualizaciones básicas bot puesta en común. Creado por UnAfraid.

diff --git a/src/main/java/org/codespartans/telegram/bot/BotThread.java b/src/main/java/org/codespartans/telegram/bot/BotThread.java
new file mode 100644
index 0000000..2ad198d
--- /dev/null
+++ b/src/main/java/org/codespartans/telegram/bot/BotThread.java
@@ -0,0 +1,100 @@
+package org.codespartans.telegram.bot;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.prefs.Preferences;
+
+import org.codespartans.telegram.bot.models.Update;
+
+/**
+ * @author UnAfraid
+ */
+public final class BotThread extends Thread {
+ private static final Preferences PREFERENCES = Preferences.userRoot();
+ private static final String UPDATE_OFFSET_KEY = "updateOffset";
+ private final Set<ITelegramListener> _listeners = ConcurrentHashMap.newKeySet();
+
+ private final TelegramBot _bot;
+ private final int _limit;
+ private final int _timeout;
+
+ /**
+ * Initializes new BotThread that will handle the message receiving
+ * @param token Each bot is given a unique authentication token <a href="https://core.telegram.org/bots#botfather">when it is created</a>.
+ *              The token looks something like 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11,
+ *              but we'll use simply <token> in this document instead.
+ *              You can learn about obtaining tokens and generating new ones in <a href="https://core.telegram.org/bots#botfather">this document</a>.
+ */
+ public BotThread(String token) {
+ this(token, 100, 0);
+ }
+
+ /**
+ * Initializes new BotThread that will handle the message receiving
+ * @param token Each bot is given a unique authentication token <a href="https://core.telegram.org/bots#botfather">when it is created</a>.
+ *              The token looks something like 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11,
+ *              but we'll use simply <token> in this document instead.
+ *              You can learn about obtaining tokens and generating new ones in <a href="https://core.telegram.org/bots#botfather">this document</a>.
+ * @param limit   Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100
+ * @param timeout Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling
+ */
+ public BotThread(String token, int limit, int timeout) {
+ super("Bot Thread");
+ _limit = limit;
+ _timeout = timeout;
+ _bot = TelegramBot.getInstance(token);
+ start();
+ }
+
+ @Override
+ public void run() {
+ try {
+ while (!isInterrupted()) {
+ try {
+ final int currentOffset = PREFERENCES.getInt(UPDATE_OFFSET_KEY, 0);
+ final List<Update> updates = _bot.getUpdates(currentOffset, _limit, _timeout);
+ for (Update update : updates) {
+ PREFERENCES.putInt(UPDATE_OFFSET_KEY, update.getUpdate_id() + 1);
+ _listeners.forEach(listener -> listener.onMessageReceived(_bot, update.getMessage()));
+ }
+ } catch (Exception e) {
+ _listeners.forEach(listener -> listener.onExceptionCaught(_bot, e));
+ }
+
+ try {
+ Thread.sleep(100);
+ } catch (Exception e) {
+ }
+ }
+ } catch (Exception e) {
+ _listeners.forEach(listener -> listener.onExceptionCaught(_bot, e));
+ }
+ }
+
+ /**
+ * Attaches listener that will be used to notify upon new message received
+ *
+ * @param listener
+ */
+ public void addListener(ITelegramListener listener) {
+ _listeners.add(listener);
+ }
+
+ /**
+ * Removes attached listener
+ *
+ * @param listener
+ */
+ public void removeListener(ITelegramListener listener) {
+ _listeners.remove(listener);
+ }
+
+ /**
+ * Interrupts the thread and stops the thread
+ */
+ public void shutdown() {
+ interrupt();
+ }
+}
diff --git a/src/main/java/org/codespartans/telegram/bot/ITelegramListener.java b/src/main/java/org/codespartans/telegram/bot/ITelegramListener.java
new file mode 100644
index 0000000..35e1e6c
--- /dev/null
+++ b/src/main/java/org/codespartans/telegram/bot/ITelegramListener.java
@@ -0,0 +1,22 @@
+package org.codespartans.telegram.bot;
+
+import org.codespartans.telegram.bot.models.Message;
+
+/**
+ * @author UnAfraid
+ */
+public interface ITelegramListener {
+ /**
+ * Invoked as soon as new message is received.
+ * @param bot
+ * @param message
+ */
+ void onMessageReceived(TelegramBot bot, Message message);
+
+ /**
+ * Invoked as soon as an exception is caught
+ * @param bot
+ * @param e
+ */
+ void onExceptionCaught(TelegramBot bot, Exception e);
+}