Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

regular expression in rivescript? #41

Open
rmasci opened this issue May 14, 2019 · 1 comment
Open

regular expression in rivescript? #41

rmasci opened this issue May 14, 2019 · 1 comment

Comments

@rmasci
Copy link

rmasci commented May 14, 2019

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
Copy link
Member

kirsle commented May 14, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants