No post anterior, descobrimos como criar um bot, inicializamos uma instância da classe Bote nos familiarizamos com os métodos de envio de mensagens usando-a.
Neste artigo, eu continuo este tópico, então recomendo começar a ler este artigo somente depois de ler a primeira parte .
Desta vez, descobriremos como reviver nosso bot e adicionar suporte de comando a ele, bem como conhecer a classe Updater.
No decorrer do artigo, iremos escrever vários bots simples, os últimos irão, de acordo com uma determinada data e código de país, determinar se um dia em um determinado país é um fim de semana ou um dia útil de acordo com o calendário de produção. Mas, como antes, o objetivo deste artigo é familiarizá-lo com a interface do pacote telegram.botpara resolver seus próprios problemas.

Todos os artigos da série "Escrevendo um bot de telegrama na linguagem R"
- Nós criamos um bot e enviamos mensagens para telegrama usando-o
- Adicionar suporte de comando e filtros de mensagem ao bot
- Como adicionar suporte de teclado ao seu bot
- Construir um diálogo consistente e lógico com o bot
- Gerenciamento de direitos de usuário de bot
Conteúdo
Updater
Updater — , , Dispetcher. Updater , ( getUpdates()), Dispetcher.
Dispetcher , .. Handler.
Handlers —
Dispetcher . telegram.bot :
- MessageHandler —
- CommandHandler —
- CallbackQueryHandler — Inline
- ErrorHandler —
,
, , , / .
, .. /hi.
library(telegram.bot)
# Updater
updater <- Updater(' ')
#
say_hello <- function(bot, update) {
#
user_name <- update$message$from$first_name
#
bot$sendMessage(update$message$chat_id,
text = paste0(" , ", user_name, "!"),
parse_mode = "Markdown")
}
#
hi_hendler <- CommandHandler('hi', say_hello)
#
updater <- updater + hi_hendler
#
updater$start_polling(), ' ' , BotFather ( ).
start_polling() Updater, , .
, /hi.

/hi, .
.

-
Updater; - , .. .
say_hello(). , — bot update, — args. bot, , , , . update , , ,getUpdates(). args , ; - , .. - . , - .
/hi,hi_hendler <- CommandHandler('hi', say_hello).CommandHandler(),hi, . ,say_hello, ; -
Updater. , ,+, ..updater <- updater + hi_hendler.add_handler(),Dispatcher, :updater$dispatcher$add_handler(); -
start_polling().
, , , - , . — MessageHandler.
MessageHandler . . /hi, , : , , , , .
- , .. . .
library(telegram.bot)
# Updater
updater <- Updater(' ')
#
##
say_hello <- function(bot, update) {
#
user_name <- update$message$from$first_name
#
bot$sendMessage(update$message$chat_id,
text = paste0(" , ", user_name, "!"),
parse_mode = "Markdown",
reply_to_message_id = update$message$message_id)
}
#
MessageFilters$hi <- BaseFilter(function(message) {
# , : , , , ,
grepl(x = message$text,
pattern = '||||',
ignore.case = TRUE)
}
)
#
hi_hendler <- CommandHandler('hi', say_hello) # hi
hi_txt_hnd <- MessageHandler(say_hello, filters = MessageFilters$hi)
#
updater <- updater +
hi_hendler +
hi_txt_hnd
#
updater$start_polling(), ' ' , BotFather ( ).
, :

, , . reply_to_message_id, sendMessage(), id . id : update$message$message_id.
, — BaseFilter():
#
MessageFilters$hi <- BaseFilter(
#
function(message) {
# ,
grepl(x = message$text,
pattern = '||||',
ignore.case = TRUE)
}
)
, MessageFilters, . MessageFilters hi, .
BaseFilter() . , — , TRUE FALSE. , , grepl() , |||| TRUE.
hi_txt_hnd <- MessageHandler(say_hello, filters = MessageFilters$hi). MessageHandler() — , , — . MessageFilters$hi.
, , hi_txt_hnd.
updater <- updater +
hi_hendler +
hi_txt_hnd
, telegram.bot MessageFilters , :
- all —
- text —
- command — , ..
/ - reply — ,
- audio —
- document —
- photo —
- sticker —
- video —
- voice —
- contact —
- location —
- venue —
- game —
| — , & . , , :
handler <- MessageHandler(callback,
MessageFilters$video | MessageFilters$photo | MessageFilters$document
)
, , . , .
, .
API isdayoff.ru.
library(telegram.bot)
# Updater
updater <- Updater(' ')
#
##
check_date <- function(bot, update, args) {
#
day <- args[1] #
country <- args[2] #
#
if ( !grepl('\\d{4}-\\d{2}-\\d{2}', day) ) {
# Send Custom Keyboard
bot$sendMessage(update$message$chat_id,
text = paste0(day, " - , --"),
parse_mode = "Markdown")
} else {
day <- as.Date(day)
# POSIXtl
y <- format(day, "%Y")
m <- format(day, "%m")
d <- format(day, "%d")
}
#
##
## ru
if ( ! country %in% c('ru', 'ua', 'by', 'kz', 'us') ) {
# Send Custom Keyboard
bot$sendMessage(update$message$chat_id,
text = paste0(country, " - , : ru, by, kz, ua, us. ."),
parse_mode = "Markdown")
country <- 'ru'
}
# API
# HTTP
url <- paste0("https://isdayoff.ru/api/getdata?",
"year=", y, "&",
"month=", m, "&",
"day=", d, "&",
"cc=", country, "&",
"pre=1&",
"covid=1")
#
res <- readLines(url)
#
out <- switch(res,
"0" = " ",
"1" = " ",
"2" = " ",
"4" = "covid-19",
"100" = " ",
"101" = " ",
"199" = " ")
#
bot$sendMessage(update$message$chat_id,
text = paste0(day, " - ", out),
parse_mode = "Markdown")
}
#
date_hendler <- CommandHandler('check_date', check_date, pass_args = TRUE)
#
updater <- updater + date_hendler
#
updater$start_polling(), ' ' , BotFather ( ).
, check_date, .
, , , . , , .
, pass_args = TRUE CommandHandler(), , bot, update — args. , . , .
, .

— .
:
- R. RStudio File, Save As....
- bin, R Path, .
- , 1 :
R CMD BATCH C:\Users\Alsey\Documents\my_bot.R. C:\Users\Alsey\Documents\my_bot.R . , , .. . , txt bat. - Windows, ,
%windir%\system32\taskschd.msc /s. . - " ...".
- "" , " ".
- "", "". " " "", bat , .
- , .
- , "".
, , , .
, , . .