Skip to content

Custom Filters

Ernest Benedito edited this page Nov 12, 2018 · 9 revisions

It is also possible to write your own filters used with MessageHandler and CommandHandler. In essence, a filter is simply a function that receives a Message instance and returns either TRUE or FALSE. If a filter evaluates to TRUE, the message will be handled.

Restricting users

For the kill example we saw in the previous page, it would be useful to filter that command so to make it accessible only for a specific <user-id>. Thereby, you could add a filter:

filter_user <- function(message){
                   message$from_user  == <user-id>
               }

Now, you could update the handler with this filter:

kill_handler <- CommandHandler('kill', kill, filter_user)

Text or command filter

Filters can also be added to the MessageFilters object. Within it, we can see that MessageFilters$text and MessageFilters$command are mutually exclusive, so we could add a filter for messages that can be either one of them. This would result as:

MessageFilters$text_or_command <- function(message){
                               !is.null(message$text)
                           }