Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Service
- public class Telebot {
- private final String API_KEY = "####################:####################################";
- private final Long GROUP_ID = -############;
- private TelegramBot bot;
- private final Map<String, BiConsumer<Long, String>> handlers = new ConcurrentHashMap<>();
- @PostConstruct
- private void postConstruct() {
- log.info("Staring telegram bot ...");
- //assign handlers
- handlers.put("/help", this::help);
- handlers.put("/echo", this::echo);
- handlers.put("/ping", this::ping);
- bot = new TelegramBot.Builder(API_KEY).build();
- bot.setUpdatesListener(updates -> {
- // process updates
- for (Update update : updates) {
- try {
- Long chatId = update.message().chat().id();
- String text = update.message().text();
- if (isEmpty(trimAllWhitespace(text))) {
- continue;
- }
- String[] commandArray = text.split("[ @]");
- if (commandArray.length > 0) {
- String command = commandArray[0];
- if (handlers.containsKey(command)) {
- String body = trimWhitespace(text.substring(command.length(), text.length()));
- handlers.get(command).accept(chatId, body);
- }
- }
- }
- catch (Exception e) {
- log.error("bot receive/handle message error: ", e);
- }
- }
- // return id of last processed update or confirm them all
- return UpdatesListener.CONFIRMED_UPDATES_ALL;
- });
- }
- // TELEGRAM BOT HANDLERS ===========================================
- private void help(Long chatId, String text) {
- String resp =
- "/help - this help" +
- "\n" + "/echo [text] - echo [text]" +
- "\n" + "/ping - echo-reply";
- SendResponse response = bot.execute(new SendMessage(chatId, resp));
- }
- private void echo(Long chatId, String text) {
- SendResponse response = bot.execute(new SendMessage(chatId, text));
- }
- private void ping(Long chatId, String text) {
- SendResponse response = bot.execute(new SendMessage(chatId, "pong"));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment