aichaos / rivescript-go

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

How to use a golang object macro #25

Closed mraaroncruz closed 7 years ago

mraaroncruz commented 7 years ago

Hi, I'm can't figure out how to use a golang object macro. On top of that I have no idea what is available in the object definition or how to inject context, if possible like in the js version.

I've tried both > object foo go and object foo golang and both give me the [ERR: Object Not Found] so I'm going to assume that it isn't supported. And I see that only javascript and text are tested.

I would love to not have to touch javascript at all. Thanks. I am getting pretty excited about rivescript.

kirsle commented 7 years ago

Hi

Because Go is a compiled language, RiveScript doesn't support in-line Go macros defined in the .rive source files. Instead, macros need to be defined in your program at compile-time using the SetSubroutine() function. Example:

package main

import (
    "fmt"
    "strings"

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

func main() {
    bot := rivescript.New(rivescript.WithUTF8())
    bot.Stream(`
        + say * to me in reverse
        - <call>reverse <star></call>
    `)
    bot.SortReplies()

    bot.SetSubroutine("reverse", func(rs *rss.RiveScript, args []string) string {
        message := []rune(strings.Join(args, " "))
        for i, j := 0, len(message)-1; i < j; i, j = i+1, j-1 {
            message[i], message[j] = message[j], message[i]
        }
        return string(message)
    })

    reply, _ := bot.Reply("user", "say hello world to me in reverse")
    fmt.Printf("Reply: %s\n", reply)
}
mraaroncruz commented 7 years ago

This is exactly what I was looking for. Thank you. I read enough source to know about bot.Stream, but didn't see the bot.SetSubroutine, perfect.