Skip to content

Context

Caleb Hiebert edited this page Nov 17, 2018 · 1 revision

Sometimes it can be useful to know what context a given user is in, enter context. Context allows you to set variables that persist on a user's conversation for a specified amount of time. In GOBBL, context comes from the bctx package.

Here is a code snippet showing how to work with context variables:

func main() {
	gobblr := gbl.New()

	// The session middleware relies on the c.User.ID property being set
	gobblr.Use(gbl.UserExtractionMiddleware())
	gobblr.Use(gbl.RequestExtractionMiddleware())

	// The context middleware relies on the
	// session middleware to store context information
	gobblr.Use(sess.Middleware(sess.MemoryStore()))

	// Add the context middleware
	gobblr.Use(bctx.Middleware())

	// Create a basic handler to test context functionality
	gobblr.Use(func(c *gbl.Context) {

		switch c.Request.Text {

		// Adding context to a conversation is quite easy,
		// simply pass in the name and the lifetime.
		// Setting the lifetime to -1 means it will live forever
		case "set":
			bctx.Add(c, "Context1", -1)
			bctx.Add(c, "Context2", 4)

		// Clearing a single context is quite easy as well
		// This will clear the context even if it's lifetime is set to -1
		case "clear":
			bctx.Clear(c, "Context1")

		// This will clear all contexts, including ones with lifetimes set to -1
		case "clear all":
			bctx.ClearAll(c)
		}

		// The context middleware stores information in the _bctxDecoded flag
		// !!! THIS FLAG SHOULD NEVER BE MODIFIED DIRECTLY !!!
		fmt.Println(c.GetFlag("_bctxDecoded"))
	})

	ci := gbl.ConsoleIntegration{}
	ci.Listen(gobblr)
}

Clone this wiki locally