all repos — disgord @ a4093084b5f92b1e3c91c66c157baba16346c4dc

A simple Discord bot in Go.

main.go (view raw)

 1package main
 2
 3import (
 4	"os"
 5	"os/signal"
 6
 7	"github.com/BiRabittoh/disgord/src"
 8	g "github.com/BiRabittoh/disgord/src/globals"
 9	"github.com/BiRabittoh/disgord/src/myconfig"
10	"github.com/BiRabittoh/disgord/src/mylog"
11	"github.com/bwmarrin/discordgo"
12)
13
14var logger = mylog.NewLogger(os.Stdout, "init", mylog.DEBUG)
15
16func messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
17	if m.Author.ID == s.State.User.ID {
18		// logger.Debugf("Ignoring own message: %s", m.Content)
19		return
20	}
21
22	logger.Debug("Got a message: " + m.Content)
23
24	response, ok, err := src.HandleCommand(s, m)
25	if err != nil {
26		logger.Errorf("could not handle command: %s", err)
27		return
28	}
29	if !ok {
30		return
31	}
32	if response == "" {
33		logger.Debug("got empty response")
34		return
35	}
36
37	_, err = s.ChannelMessageSend(m.ChannelID, response)
38	if err != nil {
39		logger.Errorf("could not send message: %s", err)
40	}
41}
42
43func readyHandler(s *discordgo.Session, r *discordgo.Ready) {
44	logger.Infof("Logged in as %s", r.User.String())
45}
46
47func main() {
48	logger.Info("Starting bot... Commit " + g.CommitID)
49	var err error
50	g.Config, err = myconfig.New[g.MyConfig]("config.json")
51	if err != nil {
52		logger.Errorf("could not load config: %s", err)
53	}
54
55	session, err := discordgo.New("Bot " + g.Config.Values.Token)
56	if err != nil {
57		logger.Fatalf("could not create bot session: %s", err)
58	}
59
60	src.InitHandlers()
61	session.AddHandler(messageHandler)
62	session.AddHandler(readyHandler)
63
64	err = session.Open()
65	if err != nil {
66		logger.Fatalf("could not open session: %s", err)
67	}
68
69	sigch := make(chan os.Signal, 1)
70	signal.Notify(sigch, os.Interrupt)
71	<-sigch
72
73	logger.Info("Stopping gracefully...")
74	err = session.Close()
75	if err != nil {
76		logger.Errorf("could not close session: %s", err)
77	}
78}