all repos — disgord @ 41b487beb8025d82e480ed8899f028ac2d381a06

A simple Discord bot in Go.

src/commands.go (view raw)

 1package src
 2
 3import (
 4	"fmt"
 5	"strings"
 6
 7	"github.com/bwmarrin/discordgo"
 8)
 9
10var (
11	handlersMap   map[string]BotCommand
12	shortCommands = map[string]string{}
13)
14
15func (bc BotCommand) FormatHelp(command, guildID string) string {
16	var shortCodeStr string
17	if bc.ShortCode != "" {
18		shortCodeStr = fmt.Sprintf(" (%s)", formatCommand(bc.ShortCode, guildID))
19	}
20	return fmt.Sprintf(helpFmt, formatCommand(command, guildID)+shortCodeStr, bc.Help)
21}
22
23func InitHandlers() {
24	handlersMap = map[string]BotCommand{
25		"echo":   {ShortCode: "e", Handler: handleEcho, Help: "echoes a message"},
26		"shoot":  {ShortCode: "sh", Handler: handleShoot, Help: "shoots a random user in your voice channel"},
27		"prefix": {Handler: handlePrefix, Help: "sets the bot's prefix for this server"},
28		"help":   {ShortCode: "h", Handler: handleHelp, Help: "shows this help message"},
29	}
30
31	for command, botCommand := range handlersMap {
32		if botCommand.ShortCode == "" {
33			continue
34		}
35		shortCommands[botCommand.ShortCode] = command
36	}
37}
38
39func HandleCommand(s *discordgo.Session, m *discordgo.MessageCreate) (response string, ok bool, err error) {
40	command, args, ok := parseUserMessage(m.Content, m.GuildID)
41	if !ok {
42		return
43	}
44
45	longCommand, short := shortCommands[command]
46	if short {
47		command = longCommand
48	}
49
50	botCommand, found := handlersMap[command]
51	if !found {
52		response = "Unknown command: " + formatCommand(command, m.GuildID)
53		return
54	}
55
56	response = botCommand.Handler(args, s, m)
57	return
58}
59
60func handleEcho(args []string, s *discordgo.Session, m *discordgo.MessageCreate) string {
61	return strings.Join(args, " ")
62}
63
64func handlePrefix(args []string, s *discordgo.Session, m *discordgo.MessageCreate) string {
65	if len(args) == 0 {
66		return "Usage: " + formatCommand("prefix <new prefix>", m.GuildID) + "."
67	}
68
69	newPrefix := args[0]
70	if len(newPrefix) > 10 {
71		return "Prefix is too long."
72	}
73
74	setPrefix(m.GuildID, newPrefix)
75
76	return "Prefix set to " + newPrefix + "."
77}
78
79func handleHelp(args []string, s *discordgo.Session, m *discordgo.MessageCreate) string {
80	helpText := "**Bot commands:**\n"
81	for command, botCommand := range handlersMap {
82		helpText += "* " + botCommand.FormatHelp(command, m.GuildID) + "\n"
83	}
84	return helpText
85}