Skip to content

How to filter incoming messages#

Installation#

python -m pip install telegram-chatbot-python

Import#

from telegram_chatbot_python import GreenAPIBot, Notification

Examples#

How to initialize an object#

bot = GreenAPIBot(
    "4100000000", "d75b3a66374942c5b3c019c698abc2067e151558acbd412345"
)

How to filter incoming messages#

Messages can be filtered by chat, by sender, by message type and text. For the chat, sender and message type filters you can use a string (str) or a list of strings (list[str]). The message text can be filtered by text, by command and by regular expressions. Below is a table with the filter names and possible values.

Filter name Description Possible values
from_chat The chat or chats to receive messages from "79876543210@c.us" or ["79876543210@c.us", "11002345678@c.us"]
from_sender The sender or senders to receive messages from "79876543210@c.us" or ["79876543210@c.us", "11002345678@c.us"]
type_message The message type or types that need to be processed "textMessage" or ["textMessage", "extendedTextMessage"]
text_message Your function will be executed if the text fully matches the text "Hello. I need help"
regexp Your function will be executed if the text fully matches the regular expression pattern r"Hello. I need help"
command Your function will be executed if the prefix and the command fully match your values "help" or ("help", "!/")

How to add filters through a decorator#

@bot.router.message(command="command")

How to add filters using a function#

bot.router.message.add_handler(handler, command="command")

How to filter messages by chat, sender or message type#

To filter messages by chat, sender or message type, you need to add a string (str) or a list of strings (list[str]).

from_chat = "79876543210@c.us"
from_sender = "79876543210@c.us"
type_message = ["textMessage", "extendedTextMessage"]

How to filter messages by message text or regular expressions#

To filter messages by message text, regular expressions or a command, you need to add a string (str).

text_message = "Hello. I need help"
regexp = r"Hello. I need help"

How to filter messages by command#

To filter messages by command, you need to add a string (str) or a tuple (tuple). You need to specify either the command name, or the command name and a string of prefixes. The default prefix is: /.

command = "help"
command = ("help", "!/")

Example#

Link to the example: filters.py.

@bot.router.message(command="help")
def message_handler(notification: Notification) -> None:
    notification.answer_with_file(file="help.png")


bot.run_forever()

Running the application#

python filters.py

The list of examples#

Description Link to the example
How to start receiving messages and replying to them base.py
How to receive other notifications and process the notification body event.py
How to filter incoming messages filters.py
A bot example full.py