From f23162d49acdbcf5d6fdb244fafff60727f1d7f9 Mon Sep 17 00:00:00 2001 From: Steve Date: Tue, 14 Apr 2020 16:54:31 -0400 Subject: [PATCH] add function dispatch --- testbot/action.go | 5 +++++ testbot/main.go | 1 + testbot/messages.go | 23 +++++++++++------------ testbot/testbot.go | 8 ++++++++ 4 files changed, 25 insertions(+), 12 deletions(-) create mode 100644 testbot/action.go diff --git a/testbot/action.go b/testbot/action.go new file mode 100644 index 0000000..f5b3eab --- /dev/null +++ b/testbot/action.go @@ -0,0 +1,5 @@ +package main + +type Action func(inputs ...string) string + +var ActionList map[string]Action diff --git a/testbot/main.go b/testbot/main.go index 93529bc..ec3f8e9 100644 --- a/testbot/main.go +++ b/testbot/main.go @@ -26,6 +26,7 @@ func main() { Conf: c, Jobs: make(chan *mautrix.Event, 100), } + tb.InitActions() syncer := botlib.NewCustomSyncer("@testbot:saintnet.tech", b.Client.Store) syncer.OnEventType(mautrix.EventMessage, tb.QueueMessage) syncer.OnEventType(mautrix.StateMember, b.DefaultHandleMember) diff --git a/testbot/messages.go b/testbot/messages.go index 7d4c74d..0aad54d 100644 --- a/testbot/messages.go +++ b/testbot/messages.go @@ -30,25 +30,24 @@ func (t *TestBot) HandleMessage(e *mautrix.Event) { if len(body_s) < 2 { return //nothing to parse } - switch body_s[1] { - case "stop": + if body_s[1] == "stop" { err := t.Message(e.RoomID, "Shutting down...") if err != nil { log.Fatal(err) } t.Shutdown() return - case "echo": - err := t.Message(e.RoomID, body) - if err != nil { - log.Fatal(err) - } - case "version": - err := t.Message(e.RoomID, "0.0.1") - if err != nil { - log.Fatal(err) - } } + response, found := ActionList[body_s[1]] + if !found { + response = func(inputs ...string) string { return "Command not found" } + } + msg := response(body_s[1:]...) + err := t.Message(e.RoomID, msg) + if err != nil { + log.Fatal(err) + } + return } func (t *TestBot) MessageHandler(cancelChan <-chan bool) { diff --git a/testbot/testbot.go b/testbot/testbot.go index 0b6cdc4..0c81ee3 100644 --- a/testbot/testbot.go +++ b/testbot/testbot.go @@ -39,3 +39,11 @@ func (t *TestBot) LoadState() { } t.Bot.ManagementRoomID = strings.Trim(string(dat), "") } + +func (t *TestBot) InitActions() { + ActionList = make(map[string]Action) + ActionList["version"] = func(inputs ...string) string { return "0.0.1" } + ActionList["echo"] = func(inputs ...string) string { + return strings.Join(inputs[:], "") + } +}