The add operator (+
, or more formally
+.TelegramObject
) is an S3 method for class
TelegramObject
that enables you to add any kind of
Handler
to an Updater
’s
Dispatcher
.
Say you want to build a bot with a simple handler for the
/start
command:
<- function(bot, update){
start $sendMessage(chat_id = update$message$chat_id,
bottext = sprintf("Hello %s!",
$message$from$first_name))
update
}
<- CommandHandler("start", start) start_handler
You can then build your updater with:
<- Updater("TOKEN") + start_handler updater
As things start to get more complex, you can chain multiple handlers in a single call:
<- function(bot, update){
echo $sendMessage(chat_id = update$message$chat_id,
bottext = update$message$text)
}
<- Updater("TOKEN") + CommandHandler("start", start) + MessageHandler(echo, MessageFilters$text) updater
And keep adding…
<- function(bot, update, args){
caps if (length(args > 0L)){
<- toupper(paste(args, collapse = " "))
text_caps $sendMessage(chat_id = update$message$chat_id,
bottext = text_caps)
}
}
<- updater + CommandHandler("caps", caps, pass_args = TRUE) updater
Give it a try! Start polling the updater:
$start_polling() updater
And send /start to the bot, /caps foo or just a simple text.
The operator is indeed calling the add_handler
method
from an Updater
’s Dispatcher
. Then:
<- updater + start_handler updater
Is equivalent to:
$dispatcher$add_handler(start_handler) updater
Also, it works with Dispatcher
objects:
<- updater$dispatcher
dispatcher <- dispatcher + start_handler dispatcher
So, all in all, the +.TelegramObject
operator simplifies
the construction of an Updater
. However, if you want to add
a handler with advanced settings, let’s say by controlling the
group
in which it is placed, you will need to make an
add_handler
call.