main.go (view raw)
1package main
2
3import (
4 "os"
5 "os/signal"
6 "strings"
7
8 "github.com/BiRabittoh/disgord/myconfig"
9 "github.com/bwmarrin/discordgo"
10)
11
12func parseUserMessage(messageContent string) (command string, args []string, ok bool) {
13 after, found := strings.CutPrefix(messageContent, config.Values.Prefix)
14 if !found {
15 return
16 }
17
18 userInput := strings.Split(after, " ")
19 command = strings.ToLower(userInput[0])
20 return command, userInput[1:], len(command) > 0
21}
22
23func handleCommand(s *discordgo.Session, m *discordgo.MessageCreate) (response string, ok bool, err error) {
24 command, args, ok := parseUserMessage(m.Content)
25 if !ok {
26 return
27 }
28
29 longCommand, short := shortCommands[command]
30 if short {
31 command = longCommand
32 }
33
34 botCommand, found := handlersMap[command]
35 if !found {
36 response = "Unknown command: " + formatCommand(command)
37 return
38 }
39
40 response = botCommand.Handler(args, s, m)
41 return
42}
43
44func messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
45 logger.Debug("got a message: " + m.Content)
46
47 response, ok, err := handleCommand(s, m)
48 if err != nil {
49 logger.Errorf("could not handle command: %s", err)
50 return
51 }
52 if !ok {
53 return
54 }
55 if response == "" {
56 logger.Debug("got empty response")
57 return
58 }
59
60 _, err = s.ChannelMessageSend(m.ChannelID, response)
61 if err != nil {
62 logger.Errorf("could not send message: %s", err)
63 }
64}
65
66func readyHandler(s *discordgo.Session, r *discordgo.Ready) {
67 logger.Infof("Logged in as %s", r.User.String())
68}
69
70func main() {
71 var err error
72 config, err = myconfig.New[Config]("config.json")
73 if err != nil {
74 logger.Errorf("could not load config: %s", err)
75 }
76
77 session, err := discordgo.New("Bot " + config.Values.Token)
78 if err != nil {
79 logger.Fatalf("could not create bot session: %s", err)
80 }
81
82 InitHandlers()
83 session.AddHandler(messageHandler)
84 session.AddHandler(readyHandler)
85
86 err = session.Open()
87 if err != nil {
88 logger.Fatalf("could not open session: %s", err)
89 }
90
91 sigch := make(chan os.Signal, 1)
92 signal.Notify(sigch, os.Interrupt)
93 <-sigch
94
95 logger.Info("Stopping gracefully...")
96 err = session.Close()
97 if err != nil {
98 logger.Errorf("could not close session: %s", err)
99 }
100}