Scrivere un bot di telegramma in R (parte 3): come aggiungere il supporto della tastiera a un bot

Questo è il terzo articolo della serie “Scrivere un bot di Telegram in R”. Nelle pubblicazioni precedenti, abbiamo imparato come creare un bot di Telegram, inviare messaggi attraverso di esso, aggiungere comandi e filtri dei messaggi al bot. Pertanto, prima di iniziare a leggere questo articolo, ti consiglio vivamente di leggerlo precedente, Perché Qui non mi soffermerò più sulle basi della creazione di bot precedentemente descritte.

In questo articolo miglioreremo l'usabilità del nostro bot aggiungendo una tastiera, che renderà l'interfaccia del bot intuitiva e facile da usare.

Scrivere un bot di telegramma in R (parte 3): come aggiungere il supporto della tastiera a un bot

Tutti gli articoli della serie "Scrivere un bot di Telegram in R"

  1. Creiamo un bot e lo utilizziamo per inviare messaggi in Telegram
  2. Aggiungi il supporto dei comandi e i filtri dei messaggi al bot
  3. Come aggiungere il supporto per la tastiera a un bot

contenuto

Se sei interessato all'analisi dei dati, potresti essere interessato al mio Telegram и youtube canali. La maggior parte del contenuto è dedicata al linguaggio R.

  1. Quali tipi di tastiere supporta il bot di Telegram?
  2. Tastiera di risposta
  3. Tastiera in linea
    3.1 Un esempio di un semplice bot con supporto per i pulsanti InLine
    3.2 Un esempio di bot che segnala il tempo attuale per una città selezionata
    3.3 Un esempio di bot che visualizza un elenco degli ultimi articoli con collegamenti all'hub specificato da habr.com
  4. conclusione

Quali tipi di tastiere supporta il bot di Telegram?

Al momento della scrittura telegram.bot permette di creare due tipologie di tastiere:

  • Rispondi: la normale tastiera principale, situata sotto il pannello di immissione del testo del messaggio. Una tastiera di questo tipo invia semplicemente un messaggio di testo al bot e come testo invierà il testo scritto sul pulsante stesso.
  • In linea: tastiera associata a un messaggio bot specifico. Questa tastiera invia al bot i dati associati al pulsante premuto; tali dati potrebbero differire dal testo scritto sul pulsante stesso. E tali pulsanti vengono elaborati CallbackQueryHandler.

Affinché il bot possa aprire la tastiera, è necessario inviare un messaggio tramite il metodo sendMessage(), passa come argomento la tastiera creata in precedenza reply_markup.

Di seguito vedremo diversi esempi.

Tastiera di risposta

Come ho scritto sopra, questa è la tastiera principale di controllo del bot.

Un esempio di creazione di una tastiera di risposta dalla guida ufficiale

bot <- Bot(token = "TOKEN")
chat_id <- "CHAT_ID"

# Create Custom Keyboard
text <- "Aren't those custom keyboards cool?"
RKM <- ReplyKeyboardMarkup(
  keyboard = list(
    list(KeyboardButton("Yes, they certainly are!")),
    list(KeyboardButton("I'm not quite sure")),
    list(KeyboardButton("No..."))
  ),
  resize_keyboard = FALSE,
  one_time_keyboard = TRUE
)

# Send Custom Keyboard
bot$sendMessage(chat_id, text, reply_markup = RKM)

Quanto sopra è un esempio tratto dalla guida ufficiale del pacchetto telegram.bot. Per creare una tastiera, utilizzare la funzione ReplyKeyboardMarkup(), che a sua volta accetta un elenco di elenchi di pulsanti creati dalla funzione KeyboardButton().

Perché dentro ReplyKeyboardMarkup() Hai bisogno di passare non solo un elenco, ma un elenco di elenchi? Il fatto è che passi l'elenco principale e in esso definisci ogni riga di pulsanti in elenchi separati, perché È possibile posizionare più pulsanti in una riga.

argomento resize_keyboard ti consente di selezionare automaticamente la dimensione ottimale dei pulsanti della tastiera e l'argomento one_time_keyboard consente di nascondere la tastiera dopo aver premuto ogni pulsante.

Scriviamo un semplice bot che avrà 3 pulsanti:

  • ID chat: richiedi l'ID chat del dialogo con il bot
  • Il mio nome - Richiedi il tuo nome
  • Il mio login: richiedi il tuo nome utente in Telegram

Codice 1: bot semplice con tastiera di risposta

library(telegram.bot)

# создаём экземпляр класса Updater
updater <- Updater('ТОКЕН ВАШЕГО БОТА')

# создаём методы
## метод для запуска клавиатуры
start <- function(bot, update) {

  # создаём клавиатуру
  RKM <- ReplyKeyboardMarkup(
    keyboard = list(
      list(KeyboardButton("Чат ID")),
      list(KeyboardButton("Моё имя")),
      list(KeyboardButton("Мой логин"))
    ),
    resize_keyboard = FALSE,
    one_time_keyboard = TRUE
  )

  # отправляем клавиатуру
  bot$sendMessage(update$message$chat_id,
                  text = 'Выберите команду', 
                  reply_markup = RKM)

}

## метод возвразающий id чата
chat_id <- function(bot, update) {

  bot$sendMessage(update$message$chat_id, 
                  text = paste0("Чат id этого диалога: ", update$message$chat_id),
                  parse_mode = "Markdown")

}

## метод возвращающий имя
my_name <- function(bot, update) {

  bot$sendMessage(update$message$chat_id, 
                  text = paste0("Вас зовут ", update$message$from$first_name),
                  parse_mode = "Markdown")

}

## метод возвращающий логин
my_username <- function(bot, update) {

  bot$sendMessage(update$message$chat_id, 
                  text = paste0("Ваш логин ", update$message$from$username),
                  parse_mode = "Markdown")

}

# создаём фильтры
## сообщения с текстом Чат ID
MessageFilters$chat_id <- BaseFilter(function(message) {

  # проверяем текст сообщения
  message$text == "Чат ID"

}
)

## сообщения с текстом Моё имя
MessageFilters$name <- BaseFilter(function(message) {

  # проверяем текст сообщения
  message$text == "Моё имя"

}
)

## сообщения с текстом Мой логин
MessageFilters$username <- BaseFilter(function(message) {

  # проверяем текст сообщения
  message$text == "Мой логин"
)

# создаём обработчики
h_start    <- CommandHandler('start', start)
h_chat_id  <- MessageHandler(chat_id, filters = MessageFilters$chat_id)
h_name     <- MessageHandler(my_name, filters = MessageFilters$name)
h_username <- MessageHandler(my_username, filters = MessageFilters$username)

# добавляем обработчики в диспетчер
updater <- updater + 
            h_start +
            h_chat_id +
            h_name +
            h_username

# запускаем бота 
updater$start_polling()

Esegui l'esempio di codice sopra, dopo aver sostituito 'IL TUO BOT TOKEN' con il token reale che hai ricevuto durante la creazione del bot tramite BotPadre (Ho parlato della creazione di un bot in primo articolo).

Dopo l'avvio, dai un comando al bot /start, Perché Questo è esattamente ciò che abbiamo definito per avviare la tastiera.

Scrivere un bot di telegramma in R (parte 3): come aggiungere il supporto della tastiera a un bot

Se al momento ti è difficile analizzare l'esempio di codice fornito, con la creazione di metodi, filtri e gestori, dovresti tornare a quello precedente Articolo, in cui ho descritto tutto questo in dettaglio.

Abbiamo creato 4 metodi:

  • start: avvia la tastiera
  • chat_id: richiede l'ID della chat
  • my_name: richiedi il tuo nome
  • my_username: richiedi il tuo accesso

Obiettare Filtri messaggi aggiunti 3 filtri dei messaggi in base al loro testo:

  • chat_id: messaggi con testo "Чат ID"
  • nome: messaggi con testo "Моё имя"
  • nomeutente: messaggi con testo "Мой логин"

E abbiamo creato 4 gestori che, in base a comandi e filtri forniti, eseguiranno i metodi specificati.

# создаём обработчики
h_start    <- CommandHandler('start', start)
h_chat_id  <- MessageHandler(chat_id, filters = MessageFilters$chat_id)
h_name     <- MessageHandler(my_name, filters = MessageFilters$name)
h_username <- MessageHandler(my_username, filters = MessageFilters$username)

La tastiera stessa viene creata all'interno del metodo start() Il gruppo ReplyKeyboardMarkup().

RKM <- ReplyKeyboardMarkup(
    keyboard = list(
      list(KeyboardButton("Чат ID")),
      list(KeyboardButton("Моё имя")),
      list(KeyboardButton("Мой логин"))
    ),
    resize_keyboard = FALSE,
    one_time_keyboard = TRUE
)

Nel nostro caso, abbiamo posizionato tutti i pulsanti uno sotto l'altro, ma possiamo disporli in una riga apportando modifiche all'elenco degli elenchi di pulsanti. Perché una riga all'interno della tastiera viene creata tramite un elenco annidato di pulsanti, quindi per visualizzare i nostri pulsanti in una riga dobbiamo riscrivere parte del codice per costruire la tastiera in questo modo:

RKM <- ReplyKeyboardMarkup(
    keyboard = list(
      list(
          KeyboardButton("Чат ID"),
          KeyboardButton("Моё имя"),
          KeyboardButton("Мой логин")
     )
    ),
    resize_keyboard = FALSE,
    one_time_keyboard = TRUE
)

Scrivere un bot di telegramma in R (parte 3): come aggiungere il supporto della tastiera a un bot

La tastiera viene inviata alla chat utilizzando il metodo sendMessage(), nell'argomentazione reply_markup.

  bot$sendMessage(update$message$chat_id,
                  text = 'Выберите команду', 
                  reply_markup = RKM)

Tastiera in linea

Come ho scritto sopra, la tastiera in linea è legata a un messaggio specifico. È un po' più difficile da usare rispetto alla tastiera principale.

Inizialmente, devi aggiungere un metodo al bot per chiamare la tastiera in linea.

Per rispondere al clic di un pulsante in linea, puoi anche utilizzare il metodo bot answerCallbackQuery(), che può visualizzare una notifica nell'interfaccia di telegramma all'utente che preme il pulsante Inline.

I dati inviati dal pulsante Inline non sono testo, quindi per elaborarli è necessario creare un gestore speciale utilizzando il comando CallbackQueryHandler().

Il codice per costruire una tastiera in linea fornito nella guida ufficiale del pacchetto telegram.bot.

Codice per costruire una tastiera in linea dalla guida ufficiale

# Initialize bot
bot <- Bot(token = "TOKEN")
chat_id <- "CHAT_ID"

# Create Inline Keyboard
text <- "Could you type their phone number, please?"
IKM <- InlineKeyboardMarkup(
  inline_keyboard = list(
    list(
      InlineKeyboardButton(1),
      InlineKeyboardButton(2),
      InlineKeyboardButton(3)
    ),
    list(
      InlineKeyboardButton(4),
      InlineKeyboardButton(5),
      InlineKeyboardButton(6)
    ),
    list(
      InlineKeyboardButton(7),
      InlineKeyboardButton(8),
      InlineKeyboardButton(9)
    ),
    list(
      InlineKeyboardButton("*"),
      InlineKeyboardButton(0),
      InlineKeyboardButton("#")
    )
  )
)

# Send Inline Keyboard
bot$sendMessage(chat_id, text, reply_markup = IKM)

È necessario creare una tastiera in linea utilizzando il comando InlineKeyboardMarkup(), secondo lo stesso principio della tastiera di risposta. IN InlineKeyboardMarkup() è necessario passare una lista di liste di pulsanti Inline, ogni singolo pulsante viene creato dalla funzione InlineKeyboardButton().

Un pulsante in linea può passare alcuni dati al bot utilizzando un argomento callback_datao aprire qualsiasi pagina HTML specificata utilizzando l'argomento url.

Il risultato sarà un elenco in cui ogni elemento è anche un elenco di pulsanti in linea che devono essere combinati in un'unica riga.

Successivamente esamineremo diversi esempi di bot con pulsanti in linea.

Un esempio di un semplice bot con supporto per i pulsanti InLine

Innanzitutto, scriveremo un bot per i test rapidi per covid-19. Per comando /test, ti invierà una tastiera con due pulsanti, a seconda del pulsante premuto ti invierà un messaggio con i risultati del tuo test.

Codice 2: il bot più semplice con tastiera in linea

library(telegram.bot)

# создаём экземпляр класса Updater
updater <- Updater('ТОКЕН ВАШЕГО БОТА')

# метод для отправки InLine клавиатуры
test <- function(bot, update) {

  # создаём InLine клавиатуру
  IKM <- InlineKeyboardMarkup(
    inline_keyboard = list(
      list(
        InlineKeyboardButton("Да", callback_data = 'yes'),
        InlineKeyboardButton("Нет", callback_data = 'no')
      )
    )
  )

  # Отправляем клавиатуру в чат
  bot$sendMessage(update$message$chat_id, 
                  text = "Вы болете коронавирусом?", 
                  reply_markup = IKM)
}

# метод для обработки нажатия кнопки
answer_cb <- function(bot, update) {

  # полученные данные с кнопки
  data <- update$callback_query$data

  # получаем имя пользователя, нажавшего кнопку
  uname <- update$effective_user()$first_name

  # обработка результата
  if ( data == 'no' ) {

    msg <- paste0(uname, ", поздравляю, ваш тест на covid-19 отрицательный.")

  } else {

    msg <- paste0(uname, ", к сожалени ваш тест на covid-19 положительный.")

  }

  # Отправка сообщения
  bot$sendMessage(chat_id = update$from_chat_id(),
                  text = msg)

  # сообщаем боту, что запрос с кнопки принят
  bot$answerCallbackQuery(callback_query_id = update$callback_query$id) 
}

# создаём обработчики
inline_h      <- CommandHandler('test', test)
query_handler <- CallbackQueryHandler(answer_cb)

# добавляем обработчики в диспетчер
updater <- updater + inline_h + query_handler

# запускаем бота
updater$start_polling()

Esegui l'esempio di codice sopra, dopo aver sostituito 'IL TUO BOT TOKEN' con il token reale che hai ricevuto durante la creazione del bot tramite BotPadre (Ho parlato della creazione di un bot in primo articolo).

Il risultato:
Scrivere un bot di telegramma in R (parte 3): come aggiungere il supporto della tastiera a un bot

Abbiamo creato due metodi:

  • test — Per inviare alla chat Tastiera in linea
  • risposta_cb — Per elaborare i dati inviati dalla tastiera.

I dati che verranno inviati da ciascun pulsante sono specificati nell'argomento callback_data, durante la creazione di un pulsante. È possibile ricevere i dati inviati dal pulsante utilizzando il costrutto update$callback_query$data, all'interno del metodo risposta_cb.

Affinché il bot reagisca alla tastiera in linea, metodo risposta_cb trattati da apposito responsabile: CallbackQueryHandler(answer_cb). Che esegue il metodo specificato quando si fa clic sul pulsante Inline. Gestore CallbackQueryHandler accetta due argomenti:

  • callback — Il metodo che deve essere eseguito
  • pattern — Filtra in base ai dati associati al pulsante utilizzando un argomento callback_data.

Di conseguenza, utilizzando l'argomento pattern Possiamo scrivere un metodo separato per premere ciascun pulsante:

Codice 3: metodi separati per ciascun pulsante in linea

library(telegram.bot)

# создаём экземпляр класса Updater
updater <- Updater('ТОКЕН ВАШЕГО БОТА')

# метод для отправки InLine клавиатуры
test <- function(bot, update) {  

  # создаём InLine клавиатуру
  IKM <- InlineKeyboardMarkup(
    inline_keyboard = list(
      list(
        InlineKeyboardButton("Да", callback_data = 'yes'),
        InlineKeyboardButton("Нет", callback_data = 'no')
      )
    )
  )

  # Отправляем клавиатуру в чат
  bot$sendMessage(update$message$chat_id, 
                  text = "Вы болете коронавирусом?", 
                  reply_markup = IKM)
}

# метод для обработки нажатия кнопки Да
answer_cb_yes <- function(bot, update) {

  # получаем имя пользователя, нажавшего кнопку
  uname <- update$effective_user()$first_name

  # обработка результата
  msg <- paste0(uname, ", к сожалени ваш текст на covid-19 положительный.")

  # Отправка сообщения
  bot$sendMessage(chat_id = update$from_chat_id(),
                  text = msg)

  # сообщаем боту, что запрос с кнопки принят
  bot$answerCallbackQuery(callback_query_id = update$callback_query$id) 
}

# метод для обработки нажатия кнопки Нет
answer_cb_no <- function(bot, update) {

  # получаем имя пользователя, нажавшего кнопку
  uname <- update$effective_user()$first_name

  msg <- paste0(uname, ", поздравляю, ваш текст на covid-19 отрицательный.")

  # Отправка сообщения
  bot$sendMessage(chat_id = update$from_chat_id(),
                  text = msg)

  # сообщаем боту, что запрос с кнопки принят
  bot$answerCallbackQuery(callback_query_id = update$callback_query$id) 
}

# создаём обработчики
inline_h          <- CommandHandler('test', test)
query_handler_yes <- CallbackQueryHandler(answer_cb_yes, pattern = 'yes')
query_handler_no  <- CallbackQueryHandler(answer_cb_no, pattern = 'no')

# добавляем обработчики в диспетчер
updater <- updater + 
            inline_h + 
            query_handler_yes +
            query_handler_no

# запускаем бота
updater$start_polling()

Esegui l'esempio di codice sopra, dopo aver sostituito 'IL TUO BOT TOKEN' con il token reale che hai ricevuto durante la creazione del bot tramite BotPadre (Ho parlato della creazione di un bot in primo articolo).

Ora abbiamo scritto 2 metodi separati, ad es. un metodo, per ogni pressione del pulsante, e utilizza l'argomento pattern, durante la creazione dei relativi gestori:

query_handler_yes <- CallbackQueryHandler(answer_cb_yes, pattern = 'yes')
query_handler_no  <- CallbackQueryHandler(answer_cb_no, pattern = 'no')

Il codice del metodo termina risposta_cb Il gruppo bot$answerCallbackQuery(callback_query_id = update$callback_query$id), che comunica al bot che i dati dalla tastiera in linea sono stati ricevuti.

Un esempio di bot che segnala il tempo attuale per una città selezionata

Proviamo a scrivere un bot che richieda dati meteorologici.

La logica del suo lavoro sarà la seguente. Inizialmente dalla squadra /start chiami la tastiera principale, che ha un solo pulsante "Meteo". Cliccando su questo pulsante riceverai un messaggio con la tastiera in linea per selezionare la città di cui vuoi conoscere il meteo attuale. Seleziona una delle città e ottieni il tempo attuale.

In questo esempio di codice utilizzeremo diversi pacchetti aggiuntivi:

Codice 4: un bot che segnala il tempo attuale per la città selezionata

library(telegram.bot)
library(httr)
library(stringr)

# создаём экземпляр класса Updater
updater <- Updater('ТОКЕН ВАШЕГО БОТА')

# создаём методы
## метод для запуска основной клавиатуры
start <- function(bot, update) {

  # создаём клавиатуру
  RKM <- ReplyKeyboardMarkup(
    keyboard = list(
      list(
        KeyboardButton("Погода")
      )
    ),
    resize_keyboard = TRUE,
    one_time_keyboard = TRUE
  )

  # отправляем клавиатуру
  bot$sendMessage(update$message$chat_id,
                  text = 'Выберите команду', 
                  reply_markup = RKM)

}

## Метод вызова Inine клавиатуры
weather <- function(bot, update) {

  IKM <- InlineKeyboardMarkup(
    inline_keyboard = list(
      list(
        InlineKeyboardButton(text = 'Москва', callback_data = 'New York,us'),
        InlineKeyboardButton(text = 'Санкт-Петербург', callback_data = 'Saint Petersburg'),
        InlineKeyboardButton(text = 'Нью-Йорк', callback_data = 'New York')
      ),
      list(
        InlineKeyboardButton(text = 'Екатеринбург', callback_data = 'Yekaterinburg,ru'),
        InlineKeyboardButton(text = 'Берлин', callback_data = 'Berlin,de'),
        InlineKeyboardButton(text = 'Париж', callback_data = 'Paris,fr')
      ),
      list(
        InlineKeyboardButton(text = 'Рим', callback_data = 'Rome,it'),
        InlineKeyboardButton(text = 'Одесса', callback_data = 'Odessa,ua'),
        InlineKeyboardButton(text = 'Киев', callback_data = 'Kyiv,fr')
      ),
      list(
        InlineKeyboardButton(text = 'Токио', callback_data = 'Tokyo'),
        InlineKeyboardButton(text = 'Амстердам', callback_data = 'Amsterdam,nl'),
        InlineKeyboardButton(text = 'Вашингтон', callback_data = 'Washington,us')
      )
    )
  )

  # Send Inline Keyboard
  bot$sendMessage(chat_id = update$message$chat_id, 
                  text = "Выберите город", 
                  reply_markup = IKM)
}

# метод для сообщения погоды
answer_cb <- function(bot, update) {

  # получаем из сообщения город
  city <- update$callback_query$data

  # отправляем запрос
  ans <- GET('https://api.openweathermap.org/data/2.5/weather', 
             query = list(q     = city,
                          lang  = 'ru',
                          units = 'metric',
                          appid = '4776568ccea136ffe4cda9f1969af340')) 

  # парсим ответ
  result <- content(ans)

  # формируем сообщение
  msg <- str_glue("{result$name} погода:n",
                  "Текущая температура: {result$main$temp}n",
                  "Скорость ветра: {result$wind$speed}n",
                  "Описание: {result$weather[[1]]$description}")

  # отправляем информацию о погоде
  bot$sendMessage(chat_id = update$from_chat_id(),
                  text    = msg)

  bot$answerCallbackQuery(callback_query_id = update$callback_query$id) 
}

# создаём фильтры
## сообщения с текстом Погода
MessageFilters$weather <- BaseFilter(function(message) {

  # проверяем текст сообщения
  message$text == "Погода"

}
)

# создаём обработчики
h_start         <- CommandHandler('start', start)
h_weather       <- MessageHandler(weather, filters = MessageFilters$weather)
h_query_handler <- CallbackQueryHandler(answer_cb)

# добавляем обработчики в диспетчер
updater <- updater + 
              h_start +
              h_weather +
              h_query_handler

# запускаем бота
updater$start_polling()

Esegui l'esempio di codice sopra, dopo aver sostituito 'IL TUO BOT TOKEN' con il token reale che hai ricevuto durante la creazione del bot tramite BotPadre (Ho parlato della creazione di un bot in primo articolo).

Di conseguenza, il nostro bot funzionerà in questo modo:
Scrivere un bot di telegramma in R (parte 3): come aggiungere il supporto della tastiera a un bot

Schematicamente, questo bot può essere rappresentato in questo modo:
Scrivere un bot di telegramma in R (parte 3): come aggiungere il supporto della tastiera a un bot

Abbiamo creato 3 metodi disponibili all'interno del nostro bot meteo:

  • inizia a — Avvia la tastiera principale del bot
  • tempo — Avvia la tastiera in linea per selezionare una città
  • risposta_cb — Il metodo principale che richiede il meteo dall'API per una determinata città e lo invia alla chat.

metodo inizia a lo lanciamo con il comando /start, che viene implementato dal gestore CommandHandler('start', start).

Per eseguire il metodo tempo abbiamo creato un filtro con lo stesso nome:

# создаём фильтры
## сообщения с текстом Погода
MessageFilters$weather <- BaseFilter(function(message) {

  # проверяем текст сообщения
  message$text == "Погода"

}
)

E chiamiamo questo metodo con il seguente gestore di messaggi: MessageHandler(weather, filters = MessageFilters$weather).

E alla fine, il nostro metodo principale risposta_cb reagisce alla pressione dei pulsanti Inline, che è implementato da un gestore speciale: CallbackQueryHandler(answer_cb).

All'interno di un metodo risposta_cb, leggiamo i dati inviati dalla tastiera e li scriviamo in una variabile city: city <- update$callback_query$data. Quindi richiediamo i dati meteorologici all'API, generiamo e inviamo un messaggio e infine utilizziamo il metodo answerCallbackQuery per informare il bot che abbiamo elaborato il clic del pulsante Inline.

Un esempio di bot che visualizza un elenco degli articoli più recenti con collegamenti all'hub specificato da habr.com.

Presento questo bot per mostrarti come visualizzare i pulsanti in linea che portano alle pagine web.

La logica di questo bot è simile al precedente; inizialmente lanciamo la tastiera principale con il comando /start. Successivamente, il bot ci fornisce un elenco di 6 hub tra cui scegliere, selezioniamo l'hub che ci interessa e riceviamo le 5 pubblicazioni più recenti dall'Hub selezionato.

Come hai capito, in questo caso dobbiamo ottenere un elenco di articoli e per questo utilizzeremo un pacchetto speciale habR, che ti consente di richiedere articoli da Habra e alcune statistiche su di essi in R.

Installa il pacchetto habR possibile solo da github, per il quale avrai bisogno di un pacchetto aggiuntivo devtools. Per installare, utilizzare il codice seguente.

install.packages('devtools')
devtools::install_github('selesnow/habR')

Ora diamo un'occhiata al codice per costruire il bot sopra descritto:

Codice 5: Un bot che visualizza un elenco degli articoli più recenti sull'Hub selezionato

library(telegram.bot)
library(habR)

# создаём экземпляр класса Updater
updater <- Updater('ТОКЕН ВАШЕГО БОТА')

# создаём методы
## метод для запуска основной клавиатуры
start <- function(bot, update) {

  # создаём клавиатуру
  RKM <- ReplyKeyboardMarkup(
    keyboard = list(
      list(
        KeyboardButton("Список статей")
      )
    ),
    resize_keyboard = TRUE,
    one_time_keyboard = TRUE
  )

  # отправляем клавиатуру
  bot$sendMessage(update$message$chat_id,
                  text = 'Выберите команду', 
                  reply_markup = RKM)

}

## Метод вызова Inine клавиатуры
habs <- function(bot, update) {

  IKM <- InlineKeyboardMarkup(
    inline_keyboard = list(
      list(
        InlineKeyboardButton(text = 'R', callback_data = 'R'),
        InlineKeyboardButton(text = 'Data Mining', callback_data = 'data_mining'),
        InlineKeyboardButton(text = 'Data Engineering', callback_data = 'data_engineering')
      ),
      list(
        InlineKeyboardButton(text = 'Big Data', callback_data = 'bigdata'),
        InlineKeyboardButton(text = 'Python', callback_data = 'python'),
        InlineKeyboardButton(text = 'Визуализация данных', callback_data = 'data_visualization')
      )
    )
  )

  # Send Inline Keyboard
  bot$sendMessage(chat_id = update$message$chat_id, 
                  text = "Выберите Хаб", 
                  reply_markup = IKM)
}

# метод для сообщения погоды
answer_cb <- function(bot, update) {

  # получаем из сообщения город
  hub <- update$callback_query$data

  # сообщение о том, что данные по кнопке получены
  bot$answerCallbackQuery(callback_query_id = update$callback_query$id, 
                          text = 'Подождите несколько минут, запрос обрабатывается') 

  # сообщение о том, что надо подождать пока бот получит данные
  mid <- bot$sendMessage(chat_id = update$from_chat_id(),
                         text    = "Подождите несколько минут пока, я соберу данные по выбранному Хабу")

  # парсим Хабр
  posts <- head(habr_hub_posts(hub, 1), 5)

  # удаляем сообщение о том, что надо подождать
  bot$deleteMessage(update$from_chat_id(), mid$message_id) 

  # формируем список кнопок
  keys <- lapply(1:5, function(x) list(InlineKeyboardButton(posts$title[x], url = posts$link[x])))

  # формируем клавиатуру
  IKM <- InlineKeyboardMarkup(
    inline_keyboard =  keys 
    )

  # отправляем информацию о погоде
  bot$sendMessage(chat_id = update$from_chat_id(),
                  text    = paste0("5 наиболее свежих статей из Хаба ", hub),
                  reply_markup = IKM)

}

# создаём фильтры
## сообщения с текстом Погода
MessageFilters$hubs <- BaseFilter(function(message) {

  # проверяем текст сообщения
  message$text == "Список статей"

}
)

# создаём обработчики
h_start         <- CommandHandler('start', start)
h_hubs          <- MessageHandler(habs, filters = MessageFilters$hubs)
h_query_handler <- CallbackQueryHandler(answer_cb)

# добавляем обработчики в диспетчер
updater <- updater + 
  h_start +
  h_hubs  +
  h_query_handler

# запускаем бота
updater$start_polling()

Esegui l'esempio di codice sopra, dopo aver sostituito 'IL TUO BOT TOKEN' con il token reale che hai ricevuto durante la creazione del bot tramite BotPadre (Ho parlato della creazione di un bot in primo articolo).

Di conseguenza, otterremo questo risultato:
Scrivere un bot di telegramma in R (parte 3): come aggiungere il supporto della tastiera a un bot

Abbiamo codificato l'elenco degli hub disponibili per la selezione nel metodo habs:

## Метод вызова Inine клавиатуры
habs <- function(bot, update) {

  IKM <- InlineKeyboardMarkup(
    inline_keyboard = list(
      list(
        InlineKeyboardButton(text = 'R', callback_data = 'r'),
        InlineKeyboardButton(text = 'Data Mining', callback_data = 'data_mining'),
        InlineKeyboardButton(text = 'Data Engineering', callback_data = 'data_engineering')
      ),
      list(
        InlineKeyboardButton(text = 'Big Data', callback_data = 'bigdata'),
        InlineKeyboardButton(text = 'Python', callback_data = 'python'),
        InlineKeyboardButton(text = 'Визуализация данных', callback_data = 'data_visualization')
      )
    )
  )

  # Send Inline Keyboard
  bot$sendMessage(chat_id = update$message$chat_id, 
                  text = "Выберите Хаб", 
                  reply_markup = IKM)
}

Otteniamo un elenco di articoli dall'Hub specificato con il comando habr_hub_posts(), dalla confezione habR. Allo stesso tempo facciamo presente che non abbiamo bisogno di un elenco di articoli per tutto il tempo, ma solo della prima pagina in cui si trovano 20 articoli. Dalla tabella risultante utilizzando il comando head() Lasciamo solo i primi 5, che sono gli articoli più recenti.

  # парсим Хабр
  posts <- head(habr_hub_posts(hub, 1), 5)

La logica è molto simile al bot precedente, ma in questo caso generiamo una tastiera Inline con la lista degli articoli in modo dinamico utilizzando la funzione lapply().

  # формируем список кнопок
  keys <- lapply(1:5, function(x) list(InlineKeyboardButton(posts$title[x], url = posts$link[x])))

  # формируем клавиатуру
  IKM <- InlineKeyboardMarkup(
    inline_keyboard =  keys 
    )

Inseriamo il titolo dell'articolo nel testo del pulsante posts$title[x]e nell'argomentazione url collegamento all'articolo: url = posts$link[x].

Successivamente, creiamo un filtro, gestori e lanciamo il nostro bot.

conclusione

Ora i robot che scrivi saranno molto più comodi da usare, perché saranno controllati dalla tastiera, piuttosto che inserendo comandi. Come minimo, quando si interagisce con un bot tramite uno smartphone, la tastiera semplificherà notevolmente il processo di utilizzo.

Nel prossimo articolo scopriremo come costruire un dialogo logico con un bot e lavorare con i database.

Fonte: habr.com

Aggiungi un commento