Escriure un bot de telegrama a R (part 3): com afegir suport de teclat a un bot

Aquest és el tercer article de la sèrie "Escriure un bot de telegrama en R". En publicacions anteriors, vam aprendre a crear un bot de telegram, enviar missatges a través d'ell, afegir ordres i filtres de missatges al bot. Per tant, abans de començar a llegir aquest article, us recomano molt que llegiu anterior, perquè Aquí ja no em detendré en els conceptes bàsics de la creació de bots descrits anteriorment.

En aquest article, millorarem la usabilitat del nostre bot afegint un teclat, que farà que la interfície del bot sigui intuïtiva i fàcil d'utilitzar.

Escriure un bot de telegrama a R (part 3): com afegir suport de teclat a un bot

Tots els articles de la sèrie "Escriure un bot de telegram en R"

  1. Creem un bot i l'utilitzem per enviar missatges a telegram
  2. Afegiu suport d'ordres i filtres de missatges al bot
  3. Com afegir suport de teclat a un bot

Contingut

Si esteu interessats en l'anàlisi de dades, potser us interessa el meu telegram и youtube canals. La major part del contingut està dedicat al llenguatge R.

  1. Quins tipus de teclats admet el bot de telegram?
  2. Teclat de resposta
  3. Teclat en línia
    3.1. Un exemple de bot senzill amb suport per als botons InLine
    3.2. Un exemple de bot que informa del temps actual d'una ciutat seleccionada
    3.3. Un exemple de bot que mostra una llista dels últims articles amb enllaços al concentrador especificat des d'habr.com
  4. Conclusió

Quins tipus de teclats admet el bot de telegram?

En el moment d'escriure aquest article telegram.bot permet crear dos tipus de teclats:

  • Resposta: el teclat principal, normal, que es troba sota el tauler d'entrada de text del missatge. Aquest teclat simplement envia un missatge de text al bot i, com a text, enviarà el text escrit al mateix botó.
  • En línia: teclat enllaçat a un missatge de bot específic. Aquest teclat envia les dades del bot associades al botó premut, aquestes dades poden diferir del text escrit al mateix botó. I aquests botons es processen CallbackQueryHandler.

Perquè el bot obri el teclat, és necessari quan s'envia un missatge a través del mètode sendMessage(), passa el teclat creat anteriorment com a argument reply_markup.

A continuació veurem diversos exemples.

Teclat de resposta

Com he escrit més amunt, aquest és el teclat de control de bot principal.

Un exemple de creació d'un teclat de resposta des de l'ajuda oficial

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)

L'anterior és un exemple de l'ajuda oficial del paquet telegram.bot. Per crear un teclat, utilitzeu la funció ReplyKeyboardMarkup(), que al seu torn pren una llista de llistes de botons que crea la funció KeyboardButton().

Per què en ReplyKeyboardMarkup() Necessites aprovar no només una llista, sinó una llista de llistes? El cas és que passeu la llista principal, i en ella definiu cada fila de botons en llistes separades, perquè Podeu col·locar diversos botons en una fila.

Argument resize_keyboard us permet seleccionar automàticament la mida òptima dels botons del teclat i l'argument one_time_keyboard us permet amagar el teclat després de prémer cada botó.

Escrivim un bot senzill que tindrà 3 botons:

  • ID de xat: sol·liciteu l'identificador de xat del diàleg amb el bot
  • El meu nom - Demana el teu nom
  • El meu inici de sessió - Sol·licita el teu nom d'usuari a Telegram

Codi 1: bot simple amb teclat de resposta

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()

Executeu l'exemple de codi anterior, després de substituir 'YOUR BOT TOKEN' amb el testimoni real que heu rebut en crear el bot mitjançant Pare Bot (Vaig parlar de crear un bot a primer article).

Després d'iniciar, doneu una ordre al bot /start, perquè Això és exactament el que hem definit per llançar el teclat.

Escriure un bot de telegrama a R (part 3): com afegir suport de teclat a un bot

Si de moment us costa analitzar l'exemple de codi donat, amb la creació de mètodes, filtres i controladors, haureu de tornar a l'anterior. article, en què vaig descriure tot això amb detall.

Hem creat 4 mètodes:

  • iniciar — Inicieu el teclat
  • chat_id — Sol·licita l'identificador de xat
  • my_name — Demana el teu nom
  • my_username — Sol·liciteu el vostre inici de sessió

Oposar-se Filtres de missatges han afegit 3 filtres de missatges segons el seu text:

  • chat_id — Missatges amb text "Чат ID"
  • nom — Missatges amb text "Моё имя"
  • nom d'usuari — Missatges amb text "Мой логин"

I vam crear 4 controladors que, basats en ordres i filtres donats, executaran els mètodes especificats.

# создаём обработчики
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)

El teclat en si es crea dins del mètode start() equip ReplyKeyboardMarkup().

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

En el nostre cas, hem col·locat tots els botons un sota l'altre, però els podem organitzar en una fila fent canvis a la llista de llistes de botons. Perquè una fila dins del teclat es crea a través d'una llista imbricada de botons, per tal de mostrar els nostres botons en una fila, hem de reescriure part del codi per construir el teclat així:

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

Escriure un bot de telegrama a R (part 3): com afegir suport de teclat a un bot

El teclat s'envia al xat mitjançant el mètode sendMessage(), en l'argument reply_markup.

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

Teclat en línia

Com he escrit més amunt, el teclat en línia està lligat a un missatge específic. És una mica més difícil de treballar que el teclat principal.

Inicialment, heu d'afegir un mètode al bot per trucar al teclat en línia.

Per respondre a un clic de botó en línia, també podeu utilitzar el mètode bot answerCallbackQuery(), que pot mostrar una notificació a la interfície del telegrama a l'usuari que prem el botó Inline.

Les dades enviades des del botó Inline no són text, de manera que per processar-les cal que creeu un controlador especial amb l'ordre CallbackQueryHandler().

El codi per construir un teclat en línia que es dóna a l'ajuda oficial del paquet telegram.bot.

Codi per construir un teclat en línia des de l'ajuda oficial

# 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)

Heu de crear un teclat en línia amb l'ordre InlineKeyboardMarkup(), amb el mateix principi que el teclat Resposta. EN InlineKeyboardMarkup() cal passar una llista de llistes de botons en línia, cada botó individual és creat per la funció InlineKeyboardButton().

Un botó en línia pot passar algunes dades al bot mitjançant un argument callback_data, o obriu qualsevol pàgina HTML especificada mitjançant l'argument url.

El resultat serà una llista en la qual cada element és també una llista de botons en línia que s'han de combinar en una fila.

A continuació, veurem diversos exemples de bots amb botons en línia.

Un exemple de bot senzill amb suport per als botons InLine

Primer, escriurem un bot per fer proves exprés de covid-19. Per ordre /test, t'enviarà un teclat amb dos botons, en funció del botó premut t'enviarà un missatge amb els resultats de la teva prova.

Codi 2: el bot més senzill amb un teclat en línia

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()

Executeu l'exemple de codi anterior, després de substituir 'YOUR BOT TOKEN' amb el testimoni real que heu rebut en crear el bot mitjançant Pare Bot (Vaig parlar de crear un bot a primer article).

Resultat:
Escriure un bot de telegrama a R (part 3): com afegir suport de teclat a un bot

Hem creat dos mètodes:

  • prova — Per enviar al xat Teclat en línia
  • resposta_cb — Per processar les dades enviades des del teclat.

Les dades que s'enviaran des de cada botó s'especifiquen a l'argument callback_data, en crear un botó. Podeu rebre les dades enviades des del botó mitjançant la construcció update$callback_query$data, dins del mètode resposta_cb.

Perquè el bot reaccioni al teclat en línia, mètode resposta_cb processat per un gestor especial: CallbackQueryHandler(answer_cb). Que executa el mètode especificat quan es fa clic al botó Inline. Manipulador CallbackQueryHandler pren dos arguments:

  • callback — El mètode que cal executar
  • pattern — Filtreu per dades que estan lligades al botó mitjançant un argument callback_data.

En conseqüència, utilitzant l'argument pattern Podem escriure un mètode independent per prémer cada botó:

Codi 3: mètodes separats per a cada botó en línia

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()

Executeu l'exemple de codi anterior, després de substituir 'YOUR BOT TOKEN' amb el testimoni real que heu rebut en crear el bot mitjançant Pare Bot (Vaig parlar de crear un bot a primer article).

Ara hem escrit 2 mètodes separats, és a dir. un mètode, per a cada botó que prem, i va utilitzar l'argument pattern, en crear els seus controladors:

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

El codi del mètode acaba resposta_cb equip bot$answerCallbackQuery(callback_query_id = update$callback_query$id), que indica al bot que s'han rebut dades del teclat en línia.

Un exemple de bot que informa del temps actual d'una ciutat seleccionada

Intentem escriure un bot que sol·liciti dades meteorològiques.

La lògica del seu treball serà la següent. Inicialment per l'equip /start truqueu al teclat principal, que només té un botó "Temporada". En fer clic en aquest botó rebràs un missatge amb el teclat en línia per seleccionar la ciutat per a la qual vols conèixer el temps actual. Seleccioneu una de les ciutats i obteniu el temps actual.

En aquest exemple de codi utilitzarem diversos paquets addicionals:

  • httr — un paquet per treballar amb sol·licituds HTTP, sobre la base del qual es construeix el treball amb qualsevol API. En el nostre cas utilitzarem l'API gratuïta openweathermap.org.
  • stringr — un paquet per treballar amb text, en el nostre cas l'utilitzarem per generar un missatge sobre el temps a la ciutat seleccionada.

Codi 4: un bot que informa del temps actual de la ciutat seleccionada

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()

Executeu l'exemple de codi anterior, després de substituir 'YOUR BOT TOKEN' amb el testimoni real que heu rebut en crear el bot mitjançant Pare Bot (Vaig parlar de crear un bot a primer article).

Com a resultat, el nostre bot funcionarà com això:
Escriure un bot de telegrama a R (part 3): com afegir suport de teclat a un bot

Esquemàticament, aquest bot es pot representar així:
Escriure un bot de telegrama a R (part 3): com afegir suport de teclat a un bot

Hem creat 3 mètodes disponibles dins del nostre bot meteorològic:

  • Començar — Inicieu el teclat del bot principal
  • temps — Inicieu el teclat en línia per seleccionar una ciutat
  • resposta_cb — El mètode principal que sol·licita el temps a l'API d'una ciutat determinada i l'envia al xat.

Mètode Començar l'iniciem amb l'ordre /start, que és implementat pel gestor CommandHandler('start', start).

Per executar un mètode temps hem creat un filtre amb el mateix nom:

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

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

}
)

I anomenem aquest mètode amb el següent gestor de missatges: MessageHandler(weather, filters = MessageFilters$weather).

I al final, el nostre mètode principal resposta_cb reacciona al prémer els botons en línia, que és implementat per un controlador especial: CallbackQueryHandler(answer_cb).

Dins d'un mètode resposta_cb, llegim les dades enviades des del teclat i les escrivim en una variable city: city <- update$callback_query$data. A continuació, sol·licitem dades meteorològiques a l'API, generem i enviem un missatge i, finalment, utilitzem el mètode answerCallbackQuery per tal d'informar el bot que hem processat el clic del botó Inline.

Un exemple de bot que mostra una llista dels darrers articles amb enllaços al concentrador especificat www.habr.com.

Us presento aquest bot per mostrar-vos com mostrar els botons en línia que condueixen a pàgines web.

La lògica d'aquest bot és semblant a l'anterior inicialment iniciem el teclat principal amb l'ordre /start. A continuació, el bot ens ofereix una llista de 6 hubs per triar, seleccionem el concentrador que ens interessa i rebem les 5 publicacions més recents del Hub seleccionat.

Com enteneu, en aquest cas hem d'obtenir una llista d'articles, i per això utilitzarem un paquet especial habR, que permet demanar articles a Habra i algunes estadístiques sobre ells a R.

Установить пакет habR només és possible des de github, per al qual necessitareu un paquet addicional devtools. Per instal·lar-lo, utilitzeu el codi següent.

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

Ara mirem el codi per crear el bot descrit anteriorment:

Codi 5: un bot que mostra una llista dels articles més recents al concentrador seleccionat

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()

Executeu l'exemple de codi anterior, després de substituir 'YOUR BOT TOKEN' amb el testimoni real que heu rebut en crear el bot mitjançant Pare Bot (Vaig parlar de crear un bot a primer article).

Com a resultat, obtindrem aquest resultat:
Escriure un bot de telegrama a R (part 3): com afegir suport de teclat a un bot

Hem codificat la llista de concentradors disponibles per a la selecció al mètode 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)
}

Obtenim una llista d'articles del concentrador especificat amb l'ordre habr_hub_posts(), del paquet habR. Al mateix temps, assenyalem que no necessitem una llista d'articles durant tot el temps, sinó només la primera pàgina on es troben 20 articles. De la taula resultant utilitzant l'ordre head() Deixem només els 5 primers, que són els articles més recents.

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

La lògica és molt semblant al bot anterior, però en aquest cas generem un teclat Inline amb una llista d'articles de forma dinàmica utilitzant la funció lapply().

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

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

Inseriu el títol de l'article al text del botó posts$title[x], i en l'argument url enllaç a l'article: url = posts$link[x].

A continuació, creem un filtre, gestors i iniciem el nostre bot.

Conclusió

Ara els bots que escriviu seran molt més còmodes d'utilitzar, a causa del fet que es controlaran des del teclat, en lloc d'introduir ordres. Com a mínim, quan interactueu amb un bot mitjançant un telèfon intel·ligent, el teclat simplificarà significativament el procés d'ús.

En el següent article descobrirem com crear un diàleg lògic amb un bot i treballar amb bases de dades.

Font: www.habr.com

Compreu allotjament fiable per a llocs amb protecció DDoS, servidors VPS VDS 🔥 Compra allotjament web fiable amb protecció DDoS, servidors VPS VDS | ProHoster