rshiny

How to configure a chatbot using the shinyChatR package?


I am trying to make a chatbot that answers "hello" to any user message. I've tried in different ways, but still have not acomplished it... Here is the package documentation and one of my failed attempts:

https://cran.r-project.org/web/packages/shinyChatR/shinyChatR.pdf

library(shiny)
library(shinyChatR)

# Define UI
ui <- fluidPage(
  titlePanel("Chatbot Demo"),
  chat_ui(id = "chat1", ui_title = "Chat Area")
)

# Define server logic
server <- function(input, output, session) {
  
  # Initialize chat server
  chat <- chat_server(
    id = "chat",
    chat_user = "Cliente",
    csv_path = "chat.csv"  # Using CSV to store messages
  )
  
  # Observe incoming messages and respond
  observeEvent(chat,{
    # Let's try a direct approach if chat_rv is not structured as initially thought
    messages <- chat$chat  # Assuming chat_rv holds data directly
    if (length(messages) > 0) {
      chat$sendBotMessage("Hello")
    }
  })
}

# Run the application
shinyApp(ui, server) 

Solution

  • Below is a slightly modified code which implements a bot who always answers "Hello!".

    enter image description here

    library(shiny)
    library(shinyChatR)
    
    csv_path <- "chat.csv"
    id_chat <- "chat1"
    id_sendMessageButton <- paste0(id_chat, "-chatFromSend")
    chat_user <- "Client"
    bot <- "Bot"
    bot_message <- "Hello!"
    
    # drop this if the chat log shall not be deleted
    if (file.exists(csv_path)) {
      file.remove(csv_path)
    }
    
    ChatData <- shinyChatR:::CSVConnection$new(csv_path, n = 100)
    
    # Define UI
    ui <- fluidPage(titlePanel("Chatbot Demo"),
                    chat_ui(id = id_chat, ui_title = "Chat Area"))
    
    # Define server logic
    server <- function(input, output, session) {
      
      # Initialize chat server
      chat <- chat_server(
        id = id_chat,
        chat_user = chat_user,
        csv_path = csv_path  # Using CSV to store messages
      )
    
      # Observe incoming messages and respond
      observeEvent(input[[id_sendMessageButton]], {
        ChatData$insert_message(user = bot,
                                message = bot_message,
                                time = strftime(Sys.time()))
      })
    }
    
    # Run the application
    shinyApp(ui, server)