CookieMod/bot.go

119 lines
3.0 KiB
Go

package main
import (
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/bwmarrin/discordgo"
badger "github.com/dgraph-io/badger/v4"
)
func CheckInstallationFolder(path string) {
if info, err := os.Stat(path); err != nil {
if info == nil {
start := time.Now()
log.Info(fmt.Sprintf("Creating folder \"%s\".", path))
err := os.Mkdir(path, 0777)
if err != nil {
log.Fatal(fmt.Sprintf("Couldn't create folder \"%s\".", path))
} else {
log.Info(fmt.Sprintf("Done! (%s)", time.Since(start).String()))
}
}
return
}
}
func Init() CookieConfig {
CheckInstallationFolder("db")
CheckInstallationFolder("backup")
CheckInstallationFolder("data")
CheckInstallationFolder("data/modules")
return ConfigCheck()
}
func main() {
ourConfig := Init()
twitchConfig = Twitch_ConfigCheck()
config = ourConfig
db, err := badger.Open(badger.DefaultOptions("db/").WithIndexCacheSize(100 << 20).WithBlockCacheSize(50 << 20))
time.Sleep(1 * time.Second)
if err != nil {
log.Fatal(err)
}
defer db.Close()
log.Info("Starting CookieMod 🍪")
session, err := discordgo.New("Bot " + config.Token)
if err != nil {
log.Fatal(err)
}
// session
session.AddHandler(messageCreate)
session.Identify.Intents = discordgo.IntentsAllWithoutPrivileged
err = session.Open()
if err != nil {
fmt.Println("error opening connection,", err)
return
}
go Twitch_Task(session)
log.Info(fmt.Sprintf("CookieMod 🍪 is running as user %s#%s. Press CTRL-C to exit.", session.State.User.Username, session.State.User.Discriminator))
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
<-sc
log.Info("CookieMod 🍪 is stopping.")
session.Close()
}
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
// don't react to own messages or messages which are not from the selected guild
if m.Author.ID == s.State.User.ID || m.GuildID != config.GuildID {
return
}
if strings.HasPrefix(m.Content, botPrefix) {
cmd := m.Content
if strings.Contains(m.Content, " ") {
// could be a command
cmd = strings.Split(m.Content, " ")[0]
}
switch strings.TrimPrefix(cmd, botPrefix) {
case "uptime":
secs := int(time.Since(started).Seconds())
mins := secs / 60
hours := mins / 60
days := hours / 24
secs -= mins*60 + (hours * 60 * 60) + (days * 24 * 60 * 60)
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("I'm running for %d days, %d hours, %d minutes and %d seconds.", days, hours, mins, secs))
case "time":
now := time.Now()
hour, min, sec := now.Hour(), now.Minute(), now.Second()
hourStr := fmt.Sprint(int(hour))
minStr := fmt.Sprint(int(min))
secStr := fmt.Sprint(int(sec))
if len(hourStr) < 2 {
hourStr = "0" + hourStr
}
if len(minStr) < 2 {
minStr = "0" + minStr
}
if len(secStr) < 2 {
secStr = "0" + secStr
}
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Current time: %s:%s:%s.", hourStr, minStr, secStr))
case "weather":
fmt.Println(config.OpenWeatherMapAPIKey)
}
}
}