aichaos / rivescript-go

A RiveScript interpreter for Go. RiveScript is a scripting language for chatterbots.
https://www.rivescript.com/
MIT License
60 stars 15 forks source link

regular expression in rivescript? #41

Open rmasci opened 5 years ago

rmasci commented 5 years ago

Hi -- Is it possible using rivescript-go to define a regular expression? I am developing a chatbot where I ask the user for information for example if I need to get a serial number that is formatted like this: 123AB6-12C3-123EF456

> topic getserialnumber 
  + lookup serial number in database
  - Please enter your serial number

  + [A-Z0-9]{6}-[A-Z0-9]{4}-[A-Z0-9]{8}
  - Cool, thank you, looking <star1> up
< topic

Is something like this possible?

kirsle commented 5 years ago

It's not officially supported, but you could use an object macro and parse the message yourself.

Before calling .Reply(), store the user's original message in a user variable and then retrieve it in an object macro. Example:

package main

import (
    "fmt"
    "log"
    "regexp"

    rivescript "github.com/aichaos/rivescript-go"
)

var bot *rivescript.RiveScript

func main() {
    bot = rivescript.New(&rivescript.Config{
        Debug: false,
    })

    bot.SetSubroutine("lookup", func(rs *rivescript.RiveScript, args []string) string {
        username, _ := rs.CurrentUser()
        msg, _ := rs.GetUservar(username, "origMsg")

        re := regexp.MustCompile(`^[A-Z0-9]{6}-[A-Z0-9]{4}-[A-Z0-9]{8}$`)
        if result := re.FindStringSubmatch(msg); len(result) > 0 {
            return fmt.Sprintf("Cool, thank you, looking %s up.", msg)
        } else {
            return "Invalid formatted serial number!"
        }
    })

    bot.Stream(`
        + lookup serial number in database
        - Please enter your serial number.

        + *
        % please enter your serial number
        - <call>lookup</call>
    `)
    bot.SortReplies()

    sendMessage("user", "Lookup serial number in database")
    sendMessage("user", "123AB6-12C3-123EF456")

    sendMessage("user", "Lookup serial number in database")
    sendMessage("user", "something invalid")
}

func sendMessage(username, message string) {
    log.Printf("%s> %s", username, message)

    // Store the original message in a user variable.
    bot.SetUservar(username, "origMsg", message)

    reply, err := bot.Reply(username, message)
    if err != nil {
        log.Printf("Error> %s", err)
    } else {
        log.Printf("Bot> %s", reply)
    }
}