ebeneditos / telegram.bot

Develop a Telegram Bot with R
https://ebeneditos.github.io/telegram.bot/
GNU General Public License v3.0
108 stars 24 forks source link

Create telegram bot buttons #14

Closed selesnow closed 4 years ago

selesnow commented 4 years ago

Hello, i want add button for run telegram bot commands, can you show minimal example of using answerCallbackQuery, or other function for handle button answer?

selesnow commented 4 years ago

My code example, but i had error when i run it.

library(telegram.bot)
updater <- Updater(token = "12345:ABCDE")

inline <- function(bot, update) {

text <- "Yes or no?"
IKM <- InlineKeyboardMarkup(
  inline_keyboard = list(
    list(
      InlineKeyboardButton("Yes", callback_data = 'yes'),
      InlineKeyboardButton("No", callback_data = 'no')
    )
  )
)

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

inline_h <- CommandHandler('inline', inline)
updater <- updater + inline_h

answer_cb <- function(bot, update) {

  data <- update$callback_query$data

  # Send Custom Keyboard
  bot$sendMessage(chat_id = update$message$chat_id, 
                  text = paste0("Hello"))

  bot$answerCallbackQuery(callback_query_id = update$update_id) 
}

query_handler <- CallbackQueryHandler(answer_cb)
updater <- updater + query_handler

updater$start_polling()

Error: Error in private$request(url, data) : Bad Request (HTTP 400).

ebeneditos commented 4 years ago

Hi @selesnow, thanks for the comment.

The main issue is you are treating the callback like a message. To fix it you should change the chat_id = update$callback_query$message$chat$id and callback_query_id = update$callback_query$id. You can also insert a text in the callback answer, e.g. text = paste("Answer recorded:", data).

Try the following function, it worked for me:

answer_cb <- function(bot, update) {

  data <- update$callback_query$data

  # Send Custom Keyboard
  bot$sendMessage(chat_id = update$callback_query$message$chat$id, 
                  text = paste0("Hello"))

  bot$answerCallbackQuery(callback_query_id = update$callback_query$id,
                          text = paste("Answer recorded:", data))
}