main.go (view raw)
1package main
2
3import (
4 "os"
5 "os/signal"
6 "strings"
7
8 "github.com/bwmarrin/discordgo"
9 "github.com/joho/godotenv"
10)
11
12func parseUserMessage(messageContent string) (command string, args []string, ok bool) {
13 after, found := strings.CutPrefix(messageContent, prefix)
14 if !found {
15 return
16 }
17
18 userInput := strings.Split(after, " ")
19 if len(userInput) == 0 {
20 return
21 }
22
23 return userInput[0], userInput[1:], true
24}
25
26func messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
27 logger.Debug("got a message: " + m.Content)
28 command, args, ok := parseUserMessage(m.Content)
29 if !ok {
30 return
31 }
32
33 var response string
34 switch command {
35 case "e", "echo":
36 response = strings.Join(args, " ")
37 default:
38 response = "unknown command: " + command
39 }
40
41 _, err := s.ChannelMessageSend(m.ChannelID, response)
42 if err != nil {
43 logger.Errorf("could not send message: %s", err)
44 }
45}
46
47func readyHandler(s *discordgo.Session, r *discordgo.Ready) {
48 logger.Infof("Logged in as %s", r.User.String())
49}
50
51func main() {
52 err := godotenv.Load()
53 if err != nil {
54 logger.Errorf("Error loading .env file: %s", err)
55 }
56
57 appID = os.Getenv("APP_ID")
58 if appID == "" {
59 logger.Fatal("Could not find Discord App ID.")
60 }
61
62 discordToken = os.Getenv("AUTH_TOKEN")
63 if discordToken == "" {
64 logger.Fatal("Could not find Discord bot token.")
65 }
66
67 session, err := discordgo.New("Bot " + discordToken)
68 if err != nil {
69 logger.Fatalf("could not create bot session: %s", err)
70 }
71
72 session.AddHandler(messageHandler)
73 session.AddHandler(readyHandler)
74
75 err = session.Open()
76 if err != nil {
77 logger.Fatalf("could not open session: %s", err)
78 }
79
80 sigch := make(chan os.Signal, 1)
81 signal.Notify(sigch, os.Interrupt)
82 <-sigch
83
84 logger.Info("Stopping gracefully...")
85 err = session.Close()
86 if err != nil {
87 logger.Errorf("could not close session: %s", err)
88 }
89}