urizen/lib/discord/dispatcher.go
2020-07-16 06:24:19 +00:00

69 lines
1.7 KiB
Go

package discord
// Dispatcher is designed specifically to ease handling of text commands
// of the form "/command options"
// For other event types, you'll need the full Discord session,
// exported as the variable `Session`.
import (
"fmt"
"strings"
"github.com/bwmarrin/discordgo"
)
type DiscordMessage func(*discordgo.Session, *discordgo.MessageCreate)
var handlers map[string]DiscordMessage
var helpHandlers map[string]DiscordMessage
// TODO: is this load-order dependent?
func init() {
handlers = make(map[string]DiscordMessage)
helpHandlers = make(map[string]DiscordMessage)
handlers["/help"] = helpDispatcher
}
func RegisterHandler(command string, handler DiscordMessage, helpHandler DiscordMessage) {
handlers[command] = handler
helpHandlers[command[1:]] = helpHandler
}
func dispatcher(session *discordgo.Session, msg *discordgo.MessageCreate) {
command := strings.Split(msg.Content, " ")[0]
if msg.Author.ID == session.State.User.ID {
return
}
if handler, ok := handlers[command]; ok {
handler(session, msg)
}
}
func helpDispatcher(session *discordgo.Session, msg *discordgo.MessageCreate) {
data := strings.Split(msg.Content, " ")[1:]
if len(data) == 0 {
printCommandList(session, msg)
return
}
command := data[0]
if handler, ok := helpHandlers[command]; ok {
handler(session, msg)
}
}
func printCommandList(session *discordgo.Session, msg *discordgo.MessageCreate) {
var output strings.Builder
output.WriteString("Here are all the commands I know about:\n\n")
for command, _ := range helpHandlers {
output.WriteString(fmt.Sprintf(" %s\n", command))
}
output.WriteString("\nType `/help <command>` For more information about a particular command.")
session.ChannelMessageSend(msg.ChannelID, output.String())
}