rivescript-go icon indicating copy to clipboard operation
rivescript-go copied to clipboard

regular expression in rivescript?

Open rmasci opened this issue 6 years ago • 1 comments

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?

rmasci avatar May 14 '19 13:05 rmasci

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

kirsle avatar May 14 '19 17:05 kirsle