Scrivemu un telegram bot in a lingua R (parte 1): Crea un bot è mandà missaghji à telegram usendu

L'audienza di Telegram cresce in modu esponenziale ogni ghjornu, questu hè facilitatu da a cunvenzione di u messenger, a presenza di canali, chats, è di sicuru a capacità di creà bots.

I botti ponu esse aduprati per scopi completamente diversi, da l'automatizazione di e cumunicazioni cù i vostri clienti à a gestione di i vostri compiti.

Essenzialmente, pudete aduprà telegramma per eseguisce ogni operazione per mezu di un bot: mandà o dumandà dati, eseguite attività nantu à u servitore, cullà l'infurmazioni in una basa di dati, mandà email, è cusì.

Pensu di scrive una seria d'articuli nantu à cumu travaglià API di telegram bot, è scrivite bots per adattà à i vostri bisogni.

Scrivemu un telegram bot in a lingua R (parte 1): Crea un bot è mandà missaghji à telegram usendu

In questu primu articulu avemu da capisce cumu creà un bot di telegramma è l'utilizanu per mandà notificazioni in telegramma.

In u risultatu, averemu un bot chì verificarà u statutu di l'ultima esecuzione di tutti i travaglii in u Scheduler Task di Windows, è vi manderà notifiche se qualcunu di elli hà fallutu.

Ma u scopu di sta serie d'articuli ùn hè micca di insignà à scrive un bot per un compitu specificu è strettu, ma in generale intruduce à a sintassi di u pacchettu. telegram.bot, è esempi di codice cù quale pudete scrive bots per risolve i vostri prublemi.

Cuntenuti

Sè vo site interessatu in l'analisi di dati, pudete esse interessatu in u mo telegram и fratii canali. A maiò parte di u cuntenutu hè dedicatu à a lingua R.

  1. Creazione di un telegram bot
  2. Stallà un pacchettu per travaglià cù un telegram bot in R
  3. Mandate missaghji da R à Telegram
  4. Configurazione di una pianificazione per l'esecuzione di scans di attività
  5. cunchiusioni

Creazione di un telegram bot

Prima, avemu bisognu di creà un bot. Questu hè fattu cù un bot speciale BotPather, andà à a lea è scrivite à u bot /start.

Dopu chì riceverete un missaghju cù una lista di cumandamenti:

Missaghju da BotFather

I can help you create and manage Telegram bots. If you're new to the Bot API, please see the manual (https://core.telegram.org/bots).

You can control me by sending these commands:

/newbot - create a new bot
/mybots - edit your bots [beta]

Edit Bots
/setname - change a bot's name
/setdescription - change bot description
/setabouttext - change bot about info
/setuserpic - change bot profile photo
/setcommands - change the list of commands
/deletebot - delete a bot

Bot Settings
/token - generate authorization token
/revoke - revoke bot access token
/setinline - toggle inline mode (https://core.telegram.org/bots/inline)
/setinlinegeo - toggle inline location requests (https://core.telegram.org/bots/inline#location-based-results)
/setinlinefeedback - change inline feedback (https://core.telegram.org/bots/inline#collecting-feedback) settings
/setjoingroups - can your bot be added to groups?
/setprivacy - toggle privacy mode (https://core.telegram.org/bots#privacy-mode) in groups

Games
/mygames - edit your games (https://core.telegram.org/bots/games) [beta]
/newgame - create a new game (https://core.telegram.org/bots/games)
/listgames - get a list of your games
/editgame - edit a game
/deletegame - delete an existing game

Per creà un novu bot, mandate u cumandamentu /newbot.

BotFather vi dumandà à entre u nome di u bot è login.

BotFather, [25.07.20 09:39]
Alright, a new bot. How are we going to call it? Please choose a name for your bot.

Alexey Seleznev, [25.07.20 09:40]
My Test Bot

BotFather, [25.07.20 09:40]
Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.

Alexey Seleznev, [25.07.20 09:40]
@my_test_bot

Pudete inserisce qualsiasi nome, ma u login deve finisce cù bot.

Sè avete fattu tuttu bè, riceverete u missaghju seguente:

Done! Congratulations on your new bot. You will find it at t.me/my_test_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.

Use this token to access the HTTP API:
123456789:abcdefghijklmnopqrstuvwxyz

For a description of the Bot API, see this page: https://core.telegram.org/bots/api

Dopu avete bisognu di u token API ricevutu, in u mo esempiu hè 123456789:abcdefghijklmnopqrstuvwxyz.

À questu passu, u travagliu preparatori per a creazione di u bot hè cumpletu.

Stallà un pacchettu per travaglià cù un telegram bot in R

Supponu chì avete digià a lingua R è l'ambiente di sviluppu RStudio installatu. Se questu ùn hè micca u casu, pudete vede questu lezzione video quantu à stallà elli.

Per travaglià cù l'API Telegram Bot, useremu u pacchettu R telegram.bot.

L'installazione di pacchetti in R hè fatta cù a funzione install.packages(), cusì per installà u pacchettu chì avemu bisognu, utilizate u cumandimu install.packages("telegram.bot").

Pudete amparà di più nantu à stallà diversi pacchetti da stu video.

Dopu avè installatu u pacchettu, avete bisognu di cunnette:

library(telegram.bot)

Mandate missaghji da R à Telegram

U bot chì avete creatu pò esse truvatu in Telegram usendu u login specificatu durante a creazione, in u mo casu hè @my_test_bot.

Mandate u bot ogni missaghju, cum'è "Hey bot". À u mumentu, avemu bisognu di questu per avè l'id di u vostru chat cù u bot.

Avà scrivemu u codice seguente in R.

library(telegram.bot)

# создаём экземпляр бота
bot <- Bot(token = "123456789:abcdefghijklmnopqrstuvwxyz")

# Запрашиваем информацию о боте
print(bot$getMe())

# Получаем обновления бота, т.е. список отправленных ему сообщений
updates <- bot$getUpdates()

# Запрашиваем идентификатор чата
# Примечание: перед запросом обновлений вы должны отправить боту сообщение
chat_id <- updates[[1L]]$from_chat_id()

Inizialmente, creamu una istanza di u nostru bot cù a funzione Bot(), u token ricevutu previamente deve esse passatu in questu cum'è argumentu.

Ùn hè micca cunsideratu megliu pratica per almacenà u token in u codice, perchè pudete almacenà in una variabile d'ambiente è leghje da ellu. Per automaticamente in u pacchettu telegram.bot U supportu per e variabili di l'ambiente di i seguenti nomi hè statu implementatu: R_TELEGRAM_BOT_ИМЯ_ВАШЕГО_БОТА. Invece di ИМЯ_ВАШЕГО_БОТА rimpiazzà u nome chì avete specificatu quandu crea, in u mo casu serà una variàbile R_TELEGRAM_BOT_My Test Bot.

Ci hè parechje manere di creà una variabile di l'ambiente; Vi dicu di u più universale è multipiattaforma. Crea in u vostru cartulare di casa (pudete truvà aduprendu u cumandamentu path.expand("~")) u schedariu di testu cù u nome .Renvironment. Pudete ancu fà questu cù u cumandimu file.edit(path.expand(file.path("~", ".Renviron"))).

È aghjunghje a seguente linea.

R_TELEGRAM_BOT_ИМЯ_ВАШЕГО_БОТА=123456789:abcdefghijklmnopqrstuvwxyz

In seguitu, pudete aduprà u token salvatu in a variabile di l'ambiente cù a funzione bot_token(), i.e. cum'è què:

bot <- Bot(token = bot_token("My Test Bot"))

Metu getUpdates()ci permette di ottene l'aghjurnamenti di u bot, i.e. missaghji chì sò stati mandati à ellu. Metudu from_chat_id(), permette di ottene l'ID di u chat da quale u messagiu hè statu mandatu. Avemu bisognu di questu ID per mandà missaghji da u bot.

In più di u chat id da l'ughjettu ottenutu da u metudu getUpdates() riceverete ancu altre informazioni utili. Per esempiu, infurmazione nantu à l'utilizatore chì hà mandatu u messagiu.

updates[[1L]]$message$from

$id
[1] 000000000

$is_bot
[1] FALSE

$first_name
[1] "Alexey"

$last_name
[1] "Seleznev"

$username
[1] "AlexeySeleznev"

$language_code
[1] "ru"

Dunque, in questa tappa avemu digià tuttu ciò chì avemu bisognu di mandà un missaghju da un bot à Telegram. Avemu aduprà u metudu sendMessage(), in quale avete bisognu di passà l'ID di chat, u testu di u messagiu è u tipu di marcatura di u testu di u messagiu. U tipu di marcatura pò esse Markdown o HTML è hè stabilitu da l'argumentu parse_mode.

# Отправка сообщения
bot$sendMessage(chat_id,
                text = "Привет, *жирный текст* _курсив_",
                parse_mode = "Markdown"
)

Nozioni di basi di furmatu Markdown:

  • U carattere grassu hè evidenziatu cù *:
    • esempiu: *жирный шритф*
    • risultatu: font grassu
  • I corsivi sò indicati da underscore:
    • esempiu: _курсив_
    • risultatu: itàlicu
  • U font monospace, chì hè generalmente utilizatu per mette in risaltu u codice di u prugramma, hè specificatu cù l'apostrofi - `:
    • esempiu: "fonte monospace".
    • risultatu: моноширинный шрифт

Principi di furmazione di marcatura HTML:
In HTML, impannillate a parte di u testu chì deve esse evidenziata in tags, per esempiu <тег>текст</тег>.

  • <tag> - tag di apertura
  • - tag di chiusura

Tag di marcatura HTML

  • <b> - font grassu
    • esempiu: <b>жирный шрифт</b>
    • effettu font grassu
  • <i> - italicu
    • esempiu: <i>курсив</i>
    • risultatu: itàlicu
  • — моноширинный шрифт
    • esempiu: моноширинный шрифт
    • risultatu: моноширинный шрифт

In più di u testu, pudete mandà un altru cuntenutu cù metudi speciali:

# Отправить изображение
bot$sendPhoto(chat_id,
  photo = "https://telegram.org/img/t_logo.png"
)

# Отправка голосового сообщения
bot$sendAudio(chat_id,
  audio = "http://www.largesound.com/ashborytour/sound/brobob.mp3"
)

# Отправить документ
bot$sendDocument(chat_id,
  document = "https://github.com/ebeneditos/telegram.bot/raw/gh-pages/docs/telegram.bot.pdf"
)

# Отправить стикер
bot$sendSticker(chat_id,
  sticker = "https://www.gstatic.com/webp/gallery/1.webp"
)

# Отправить видео
bot$sendVideo(chat_id,
  video = "http://techslides.com/demos/sample-videos/small.mp4"
)

# Отправить gif анимацию
bot$sendAnimation(chat_id,
  animation = "https://media.giphy.com/media/sIIhZliB2McAo/giphy.gif"
)

# Отправить локацию
bot$sendLocation(chat_id,
  latitude = 51.521727,
  longitude = -0.117255
)

# Имитация действия в чате
bot$sendChatAction(chat_id,
  action = "typing"
)

Quelli. per esempiu usendu u metudu sendPhoto() pudete mandà un graficu salvatu cum'è una maghjina chì avete creatu cù u pacchettu ggplot2.

Verificate u Task Scheduler di Windows è invià notifiche nantu à e attività chì anu terminatu anormalmente

Per travaglià cù Windows Task Scheduler avete bisognu di stallà u pacchettu taskscheduleR, è per a cunvenzione di travaglià cù dati, installate u pacchettu dplyr.

# Установка пакетов
install.packages(c('taskscheduleR', 'dplyr'))
# Подключение пакетов
library(taskscheduleR)
library(dplyr)

Dopu, usendu a funzione taskscheduler_ls() dumandemu infurmazione nantu à e attività da u nostru pianificatore. Utilizà a funzione filter() da u pacchettu dplyr Eliminate da a lista di i travaglii quelli chì sò stati cumpletati cù successu è avè un statutu di l'ultimu risultatu di 0, è quelli chì ùn sò mai stati lanciati è anu un statutu di 267011, i travaglii disabilitati è i travaglii chì sò attualmente in esecuzione.

# запрашиваем список задач
task <- task <- taskscheduler_ls() %>%
        filter(! `Last Result`  %in% c("0", "267011") & 
               `Scheduled Task State` == "Enabled" & 
               Status != "Running") %>%
        select(TaskName) %>%
        unique() %>%
        unlist() %>%
        paste0(., collapse = "n")

In l'ughjettu task Avemu avà una lista di i travaglii chì anu fallutu, avemu bisognu di mandà sta lista à Telegram.

Se guardemu ogni cumanda in più dettagliu, allora:

  • filter() - filtra a lista di i travaglii secondu e cundizioni descritte sopra
  • select() - lascia solu un campu in a tavula cù u nome di i travaglii
  • unique() - elimina i nomi duplicati
  • unlist() - cunverte a colonna di a tavula scelta in un vettore
  • paste0() - culliga i nomi di i travaglii in una linea, è mette un alimentazione di linea cum'è separatore, i.e. n.

Tuttu ciò chì resta per noi hè di mandà stu risultatu via telegramma.

bot$sendMessage(chat_id,
                text = task,
                parse_mode = "Markdown"
)

Dunque, à u mumentu, u codice di u bot s'assumiglia cusì:

Task review bot code

# Подключение пакета
library(telegram.bot)
library(taskscheduleR)
library(dplyr)

# инициализируем бота
bot <- Bot(token = "123456789:abcdefghijklmnopqrstuvwxyz")

# идентификатор чата
chat_id <- 123456789

# запрашиваем список задач
task <- taskscheduler_ls() %>%
        filter(! `Last Result`  %in% c("0", "267011")  &
               `Scheduled Task State` == "Enabled" & 
               Status != "Running") %>%
        select(TaskName) %>%
        unique() %>%
        unlist() %>%
        paste0(., collapse = "n")

# если есть проблемные задачи отправляем сообщение
if ( task != "" ) {

  bot$sendMessage(chat_id,
                  text = task,
                  parse_mode = "Markdown"
  )

}

Quandu aduprate l'esempiu sopra, sustituisce u vostru token di bot è u vostru ID di chat in u codice.

Pudete aghjunghje e cundizioni per filtrà i travaglii, per esempiu, cuntrollà solu quelli compiti chì avete creatu, escludendu quelli di u sistema.

Pudete ancu mette diverse paràmetri in un schedariu di cunfigurazione separatu, è almacenà l'ID di chat è u token in questu. Pudete leghje a cunfigurazione, per esempiu, usendu u pacchettu configr.

Esempiu ini config

[telegram_bot]
;настройки телеграм бота и чата, в который будут приходить уведомления
chat_id=12345678
bot_token=123456789:abcdefghijklmnopqrstuvwxyz"

Un esempiu di leghje variabili da una cunfigurazione in R

library(configr)

# чтение конфина
config <- read.config('C:/путь_к_конфигу/config.cfg', rcmd.parse = TRUE)

bot_token <- config$telegram_bot$bot_token
chat_id     <- config$telegram_bot$chat_id

Configurazione di un calendariu per l'esecuzione di scans di attività

U prucessu di stallà u lanciamentu di scripts nantu à un calendariu hè descrittu in più detail in questu articulu. Quì vi descriveraghju solu i passi chì deve esse seguitu per questu. Se qualchissia di i passi ùn hè micca chjaru per voi, allora riferite à l'articulu à quale aghju furnitu un ligame.

Assumimu chì avemu salvatu u nostru codice bot in un schedariu check_bot.R. Per programà stu schedariu per esse esecutatu regularmente, seguitate questi passi:

  1. Scrivite u percorsu à u cartulare in quale R hè stallatu in a variabile di u sistema Path; in Windows, u percorsu serà qualcosa cusì: C:Program FilesRR-4.0.2bin.
  2. Crea un schedariu bat eseguibile cù una sola linea R CMD BATCH C:rscriptscheck_botcheck_bot.R. Sustituisce C:rscriptscheck_botcheck_bot.R à u percorsu sanu à u vostru schedariu R.
  3. Dopu, aduprate Windows Task Scheduler per stabilisce un calendariu di lanciamentu, per esempiu, ogni meza ora.

cunchiusioni

In questu articulu, avemu capitu cumu creà un bot è aduprà per mandà diverse notificazioni in telegramma.

Aghju descrittu u compitu di monitorà u Windows Task Scheduler, ma pudete aduprà u materiale in questu articulu per mandà qualsiasi notifiche, da a previsione di u tempu à e quotazioni in borsa, perchè R permette di cunnette cù un gran numaru di fonti di dati.

In u prossimu articulu, avemu da capisce cumu aghjunghje cumandamenti è un teclatu à u bot in modu chì ùn pò micca solu mandà notificazioni, ma ancu fà azzione più cumplessa.

Source: www.habr.com

Add a comment