[go: up one dir, main page]

Skip to content

How to filter incoming messages#

Installation#

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

How to filter incoming messages#

Filtering by webhook type occurs automatically at the handler creation level, for example - event.go. Other types of filters are implemented using the Filter method, which takes map[string][]string{} as a parameter. The key of this map is a string with the name of the parameter by which filtering will occur, the value of the map is a slice with a set of expected values. If there are several expected values in the filter for a parameter, then the method returns true if at least one expected value matches the webhook field. If a method filters several parameters at the same time, the method returns true only if all parameters pass the test.

Names of parameters for filtering Description
text Filter by message text, if at least one of the expected values matches, returns true
text_regex Filter by message text, but by regex pattern, if at least one pattern in the slice matches, returns true
sender Returns true if at least one expected value equals the message sender ID
chatId Returns true if at least one expected value equals the message's chat ID
messageType Returns true if at least one expected value is equal to the value of the messageType field in the webhook

Link to example: filter.go.

package filter

import cb "github.com/green-api/whatsapp_chatbot_golang"

type StartScene struct {
}

func (s StartScene) Start(bot *cb.Bot) {
    bot.IncomingMessageHandler(func(message *cb.Notification) {
        if message.Filter(map[string][]string{"text": {"1"}}) {
            message.AnswerWithText("This message text equals \"1\"")
        }

        if message.Filter(map[string][]string{"text_regex": {"\\d+"}}) {
            message.AnswerWithText("This message has only digits!")
        }

        if message.Filter(map[string][]string{"text_regex": {"6"}}) {
            message.AnswerWithText("This message contains \"6\" in the text")
        }

        if message.Filter(map[string][]string{"text": {"hi"}, "messageType": {"textMessage", "extendedTextMessage"}}) {
            message.AnswerWithText("This message is a \"textMessage\" or \"extendedTextMessage\", and text equals \"hi\"")
        }
    })
}

List of examples#

Description Link to example
How to initialize a handler base.go
How to initialize a scene baseScene.go
Scene "Echo" echo.go
How to receive other types of notifications event.go
How to filter incoming messages filter.go
How to work with bot state state.go
Example of a ready-made chat bot full.go