Skip to content

How to filter incoming messages#


Before you begin, you need to install the library and configure the bot; this process is described in detail here: How to import the library and configure your bot.

How to filter incoming messages and process notification bodies#

Filtering by webhook type occurs automatically by overriding the necessary methods, as described in paragraph: How to receive other notifications, but how to filter by post type?

Since each notification is automatically converted to a java object, you can filter messages by any field yourself. A description of the structure of notification objects can be found at this link: Documentation

For convenience, all java objects and fields are named similarly to the documentation:

Java объект Webhook's json объект
TextMessageWebhook TextMessage
TemplateMessageWebhook TemplateMessage
StickerMessageWebhook StickerMessage
ReactionMessageWebhook ReactionMessage
QuotedMessageWebhook QuotedMessage
PollUpdateMessageWebhook PollUpdateMessage
PollMessageWebhook PollMessage
LocationMessageWebhook LocationMessage
ListMessageWebhook ListMessage
GroupInviteMessageWebhook GroupInviteMessage
FileMessageWebhook imageMessage, videoMessage, documentMessage, audioMessage
ExtendedTextMessageWebhook ExtendedTextMessage
ButtonsMessageWebhook ButtonsMessage
ContactMessageWebhook ContactMessage
ContactsArrayMessageWebhook ContactMessage
TemplateButtonsReplyMessageWebhook TemplateButtonsReplyMessage
ButtonsResponseMessageWebhook ButtonsResponseMessage
ListResponseMessageWebhook ListResponseMessage

You can independently check whether the notification has the type you need and cast the incoming webhook to its class, receiving all its fields.

Link to example:

public class MediaStartScene extends Scene {
     public State processIncomingMessage(MessageWebhook incomingMessage, State currentState) {
         if (incomingMessage instanceof ContactMessageWebhook) {
             answerWithText(incomingMessage, "This is a contact message");

         } else if (incomingMessage instanceof LocationMessageWebhook) {
             answerWithText(incomingMessage, "This is location message");

         } else if (incomingMessage instanceof FileMessageWebhook) {
             answerWithText(incomingMessage, "This is a message with a file");

         return currentState;

You can also filter messages by text using the methods of the Scene class. Methods that begin with answerWith... are overloaded, they have the most built-in popular filters based on the text of an incoming message. Examples of using methods of this class will be described below. If you want to set a condition without executing methods class Scene, you can use the methods of the Filter class of this library, which return a boolean value:

Filter name Description
Filter.isSenderIdExpected(MessageWebhook messageWebhook, String expectedSenderId) Returns true, if expectedSenderId equals the SenderId in messageWebhook
Filter.isMessageTextRegex(MessageWebhook messageWebhook, Pattern regexPattern) Returns true, if regexPattern matches the text in messageWebhook
Filter.isMessageTextExpected(MessageWebhook messageWebhook, String expectedMessage) Returns true, if expectedMessage equals the test in messageWebhook

Example of using built-in filters#

In this example, the bot will send a message and a file in response to the rates command. Sending a message using the answerWithText() method is triggered only in response to the rates command due to the fact that the third parameter to the answerWithText method the string "rates" is passed. This mechanism is implemented in all methods of the Scene class. If you want to answer everything messages, no filter, just don't specify the third parameter. You can also pass a regex pattern as the third parameter instead of a string.

Uploading a file using the answerWithUploadFile() method is triggered only in response to the rates command due to the fact that the method is located in the if block in the condition of which the method is executed Filter.isMessageTextExpected(incomingMessage, "rates").

Link to example:

public class FiltersStartScene extends Scene {
     public State processIncomingMessage(MessageWebhook incomingMessage, State currentState) {

         answerWithText(incomingMessage, "You see this because you wrote \"rates\"", "rates"); //filtering by overloaded method

         if (Filter.isMessageTextExpected(incomingMessage, "rates")) { //filtering using the Filter class method
             answerWithUploadFile(incomingMessage, new File("src/main/resources/data/rates.png"));

         return currentState;

Full list of scene methods:#

Methods of Scene.class Описание
activateNextScene(State currentState, Scene nextScene) Активирует следующую сцену nextScene для текущего чата.
activateStartScene(State currentState) Активирует стартовую сцену для текущего пользователя.
getText(MessageWebhook messageWebhook) Возвращает текст сообщения, если оно текстовое, если нет возвращает null
answerWithText(MessageWebhook messageWebhook, String text) Отвечает текстом на входящее сообщение.
answerWithUploadFile(MessageWebhook messageWebhook, String caption, File file) Загружает и отправляет файл в ответ на входящее сообщение. Сaption - не обязательное поле.
answerWithUrlFile(MessageWebhook messageWebhook, String caption, String url, String fileName) Отправляет файл из url в ответ на входящее сообщение. Сaption - не обязательное поле.
answerWithLocation(MessageWebhook messageWebhook, String nameLocation, String address, Double latitude, Double longitude) Отправляет геолокация в ответ на входящее сообщение.
answerWithPoll(MessageWebhook messageWebhook, String message, List<Option> options, Boolean multipleAnswers) Отправляет опрос в ответ на входящее сообщение.
answerWithContact(MessageWebhook messageWebhook, Contact contact) Отправляет контакт в ответ на входящее сообщение.

In the overloaded version, message response methods may contain additional expectedMessage parameters and regexPattern, if the text of the incoming message matches the condition, the method will be executed and return the method response according to the documentation; if not, the method will return null.

List of examples#

Description Example link
How to initialize an object
Scene "Hello"
Scene "Echo"
How to receive other types of notifications
How to filter incoming messages
How to handle notification body
How to work with bot state state
Example of a ready-made chat-bot full