#' ConnectTelegram
#'
#' @param config.path
#'
#' @return telegram::TGBot
#' @export
#' @examples
ConnectTelegram <- function() {
bot.name <- telegram.cnf$bot.name
## Create the bot object
err <- 0
repeat {
telegram.bot <<- telegram::TGBot$new(token = telegram::bot_token(bot.name))
sink("NUL")
bot.me <- jsonlite::fromJSON(rawToChar(telegram.bot$getMe()$content))
sink()
if (bot.me$result$username == bot.name) {
break
}
else {
if (err == 10) {
return(FALSE)
}
Sys.sleep(10)
err <- err + 1
}
}
return(TRUE)
}
#' TellMe
#'
#' @param chat.id
#'
#' @return data.frame with message.id, name, text
#' @export
#' @examples
TellMe <- function(chat.id = 0) {
## Get Messages from chat
msgs <- telegram.bot$getUpdates()
msgs <- msgs[msgs$message$chat$id == chat.id,]
df <- as.data.frame.matrix(cbind(message.id = msgs$message$message_id,
name = msgs$message$from$first_name,
text = msgs$message$text),
stringsAsFactors = FALSE)
df$message.id <- as.numeric(df$message.id)
## Remove analyzed messages
last <- GetLastPoint(df)
if (last <= nrow(df)) {
df <- df[last:nrow(df),]
} else {
saveRDS(object = df$message.id[nrow(df)], file = "inst/extdata/telegram_id.rds")
df <- data.frame(message.id = as.numeric(),
name = as.character(),
text = as.character(),
stringsAsFactors = FALSE)
}
return(df)
}
#' GetLastPoint
#'
#' @param path
#'
#' @return
#' @export
#' @examples
GetLastPoint <- function(df){
if (file.exists("inst/extdata/telegram_id.rds")) {
last.msg.id <- readRDS(file = "inst/extdata/telegram_id.rds")
} else {
last.msg.id <- 0
}
if (!is.na(last.msg.id) & any(df$message.id == last.msg.id)) {
num.row <- as.numeric(row.names(df[df$message.id == last.msg.id, ])) + 1
} else {
# some messages lost from last connection
num.row <- 1
}
return(num.row)
}
#' CheatIt
#'
#' @param text
#'
#' @return
#' @export
#'
#' @examples
CheatIt <-function(text = "text", chat = 0) {
if (chat != 0) {
telegram.bot$set_default_chat_id(chat)
telegram.bot$sendMessage(text)
}
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.