HwidBot/main.go
2024-07-06 17:16:13 +02:00

116 lines
2.0 KiB
Go

package main
import (
"fmt"
"log"
"os"
"os/signal"
"syscall"
"database/sql"
"github.com/BurntSushi/toml"
"github.com/bwmarrin/discordgo"
_ "github.com/lib/pq"
)
var (
config Config
client *discordgo.Session
db *sql.DB
)
type Config struct {
Discord Discord `toml:"discord"`
Database Database `toml:"database"`
}
type Discord struct {
Token string `toml:"client"`
GuildID string `toml:"guildid"`
}
type Database struct {
Host string `toml:"host"`
Port int `toml:"port"`
Name string `toml:"name"`
Username string `toml:"username"`
Password string `toml:"password"`
}
func loadConfig(filename string) (Config, error) {
var config Config
_, err := toml.DecodeFile(filename, &config)
return config, err
}
func connectDb(config Config) {
var err error
connectionString := fmt.Sprintf(
"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
config.Database.Host,
config.Database.Port,
config.Database.Username,
config.Database.Password,
config.Database.Name,
)
log.Println(connectionString)
db, err := sql.Open("postgres", connectionString)
if err != nil {
log.Fatalf("Error connecting to the database: %v", err)
}
defer db.Close()
err = db.Ping()
if err != nil {
log.Fatalf("Error pinging the database: %v", err)
}
}
func init() {
var err error
config, err = loadConfig("config.toml")
if err != nil {
log.Println("Error occurred whilst trying to load config:", err)
return
}
client, err = discordgo.New("Bot " + config.Discord.Token)
if err != nil {
log.Println("Error initializing bot:", err)
return
}
connectDb(config)
}
func main() {
if client == nil {
log.Println("Bot client is not initialized")
return
}
client.AddHandler(func(client *discordgo.Session, r *discordgo.Ready) {
log.Println("Bot is online")
})
err := client.Open()
if err != nil {
log.Println("Error opening connection:", err)
return
}
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
<-stop
log.Println("Gracefully shutting down.")
client.Close()
}