all repos — disgord @ 3a034bb6b48b5d3c4f3a82de32d6832dced7f99b

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