Search in sources :

Example 1 with Update

use of com.pengrad.telegrambot.model.Update in project anton-pavlovich-bot by wyvie.

the class MessageReader method readMessages.

@Scheduled(fixedDelay = 200)
public void readMessages() {
    GetUpdates getUpdates = new GetUpdates().limit(telegramProperties.getUpdateLimit()).offset(lastOffset).timeout(0);
    GetUpdatesResponse response = telegramBot.execute(getUpdates);
    List<Update> updates = response.updates();
    updates.forEach(update -> {
        lastOffset = update.updateId() + 1;
        Message message = update.message();
        if (message != null && message.from() != null && bannedUsers.contains(message.from().id())) {
            logger.debug("Message ignored from user " + message.from().id());
            persistUser(message.from());
            return;
        }
        if (message != null && message.text() != null) {
            logger.debug("Got message '" + message.text() + "' from chat_id " + message.chat().id());
            persistUser(message.from());
            if (validateCommmand(message))
                commandProcessor.processCommand(message);
            else {
                String messageText;
                messageText = message.text().trim();
                if (messageText.startsWith("+") || messageText.startsWith("-") || emojiHelper.isThumbsUp(messageText) || emojiHelper.isThumbsDown(messageText))
                    commandProcessor.processKarma(message);
            }
            lastOffset = update.updateId() + 1;
        }
        if (message != null && message.sticker() != null) {
            String emoji = message.sticker().emoji();
            if (emojiHelper.isThumbsDown(emoji) || emojiHelper.isThumbsUp(emoji)) {
                commandProcessor.processKarma(message);
            }
        }
    });
}
Also used : GetUpdates(com.pengrad.telegrambot.request.GetUpdates) Message(com.pengrad.telegrambot.model.Message) GetUpdatesResponse(com.pengrad.telegrambot.response.GetUpdatesResponse) Update(com.pengrad.telegrambot.model.Update) Scheduled(org.springframework.scheduling.annotation.Scheduled)

Example 2 with Update

use of com.pengrad.telegrambot.model.Update in project cryptonomica by Cryptonomica.

the class TelegramWebhookServlet method doPost.

/*
     * to receive information using Telegram webhook ( Update object)
     * Telegram: "Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url,
     * containing a JSON-serialized Update. // see: Update object description on https://core.telegram.org/bots/api#update
     * In case of an unsuccessful request, we will give up after a reasonable amount of attempts"
     * https://core.telegram.org/bots/api#setwebhook
     *
     * */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    TelegramBot cryptonomicaBot = TelegramBotFactory.getCryptonomicaBot();
    // see:
    // https://github.com/pengrad/java-telegram-bot-api#webhook
    java.io.Reader reader = request.getReader();
    // or from java.io.Reader
    Update update = BotUtils.parseUpdate(reader);
    Message message = update.message();
    String messageText = message.text();
    Integer message_id = message.messageId();
    Chat chat = message.chat();
    Long chat_id = chat.id();
    String textToSend = null;
    Keyboard replyMarkup = null;
    if (messageText.equalsIgnoreCase("/start")) {
        textToSend = "Hi, I'm Cryptonomica Bot.\n" + "Nice to meet you, " + message.from().firstName() + " " + message.from().lastName() + ". " + "if you need more info, type: /moreInfo \n" + "if you want to start from the beginning, type: /start \n";
        // replyMarkup = new ForceReply();
        replyMarkup = new ReplyKeyboardRemove();
    } else if (messageText.equalsIgnoreCase("/moreInfo")) {
        textToSend = "please visit my web-app: [Cryptonomica.net](https://cryptonomica.net) ";
        // <<< needed!
        replyMarkup = new ReplyKeyboardRemove();
    } else if (message.chat().id() != TelegramBotFactory.getCryptonomicaAdminsChatId()) {
        textToSend = "really, " + message.text() + "?\n";
        // <<< needed!
        replyMarkup = new ReplyKeyboardRemove();
    }
    if (textToSend != null) {
        LOG.warning("sending message: " + textToSend + " to chat: " + message.chat().id() + " in respond to message '" + messageText + "' from " + message.from().username());
        // see message params on
        // https://core.telegram.org/bots/api#message
        SendMessage sendMessageRequest = new SendMessage(// chat id
        message.chat().id(), textToSend).parseMode(ParseMode.Markdown).disableWebPagePreview(false).disableNotification(// ?
        false).replyToMessageId(message.messageId()).replyMarkup(replyMarkup);
        LOG.warning(CollectionsService.mapToString(sendMessageRequest.getParameters()));
        SendResponse sendResponse = cryptonomicaBot.execute(sendMessageRequest);
        LOG.warning(sendResponse.toString());
    }
    ServletUtils.sendJsonResponse(response, "{}");
/*
        // this works faster:
        //
        // check url key:
        final String CryptonomicaBotTelegramUrlKey = ServletUtils.getUrlKey(request);
        final String TELEGRAM_URL_KEY = ApiKeysUtils.getApiKey("CryptonomicaBotTelegramUrlKey");
        if (!TELEGRAM_URL_KEY.equalsIgnoreCase(CryptonomicaBotTelegramUrlKey)) {
            throw new ServletException("CryptonomicaBotTelegramUrlKey is invalid");
        }

        // Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update
        // ( https://core.telegram.org/bots/api#setwebhook )
        // Update is an object that represents an incoming update
        // ( https://core.telegram.org/bots/api#update )
        JSONObject updateJsonObject = ServletUtils.getJsonObjectFromRequestWithIOUtils(request);
        JSONObject message = updateJsonObject.getJSONObject("message");
        // message_id represented by int:
        int message_id = message.getInt("message_id");
        // the actual UTF-8 text of the message, 0-4096 characters.
        String text = message.getString("text");
        JSONObject chat = message.getJSONObject("chat");
        // chat_id represented by int:
        int chat_id = chat.getInt("id");
        JSONObject from = message.getJSONObject("from");

        LOG.warning("message: " + message.toString());
        LOG.warning("message_id: " + message_id);
        LOG.warning("message text: " + text);
        LOG.warning("chat: " + chat.toString());
        LOG.warning("chat_id: " + chat_id);
        LOG.warning("from: " + from.toString());

        // see:
        // https://core.telegram.org/bots/api#sendmessage
        Map<String, String> parameterMap = new HashMap<>();
        String sendMessageText = "really, " + text + "?";
        parameterMap.put("text", sendMessageText);
        parameterMap.put("chat_id", Integer.toString(chat_id));
        parameterMap.put("reply_to_message_id", Integer.toString(message_id));

        HTTPResponse httpResponse = CryptonomicaBot.sendMessageWithParameterMap(parameterMap);
        LOG.warning("httpResponse: " + httpResponse);

        ServletUtils.sendJsonResponse(response, "O.K.");
       */
}
Also used : SendMessage(com.pengrad.telegrambot.request.SendMessage) Message(com.pengrad.telegrambot.model.Message) Keyboard(com.pengrad.telegrambot.model.request.Keyboard) SendResponse(com.pengrad.telegrambot.response.SendResponse) TelegramBot(com.pengrad.telegrambot.TelegramBot) Update(com.pengrad.telegrambot.model.Update) Chat(com.pengrad.telegrambot.model.Chat) ReplyKeyboardRemove(com.pengrad.telegrambot.model.request.ReplyKeyboardRemove) SendMessage(com.pengrad.telegrambot.request.SendMessage)

Aggregations

Message (com.pengrad.telegrambot.model.Message)2 Update (com.pengrad.telegrambot.model.Update)2 TelegramBot (com.pengrad.telegrambot.TelegramBot)1 Chat (com.pengrad.telegrambot.model.Chat)1 Keyboard (com.pengrad.telegrambot.model.request.Keyboard)1 ReplyKeyboardRemove (com.pengrad.telegrambot.model.request.ReplyKeyboardRemove)1 GetUpdates (com.pengrad.telegrambot.request.GetUpdates)1 SendMessage (com.pengrad.telegrambot.request.SendMessage)1 GetUpdatesResponse (com.pengrad.telegrambot.response.GetUpdatesResponse)1 SendResponse (com.pengrad.telegrambot.response.SendResponse)1 Scheduled (org.springframework.scheduling.annotation.Scheduled)1