-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
88 lines (73 loc) · 2.01 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"context"
"database/sql"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/bwmarrin/discordgo"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
"github.com/jackc/pgx/v4"
)
var dbConn *pgx.Conn
func init() {
db, err := sql.Open("postgres", os.Getenv("DATABASE_URL"))
if err != nil {
fmt.Println("Error preparing database connection for migration: ", err)
os.Exit(1)
}
driver, err := postgres.WithInstance(db, &postgres.Config{})
if err != nil {
fmt.Println("Error preparing database driver for migration: ", err)
os.Exit(1)
}
migration, err := migrate.NewWithDatabaseInstance("file://migrations", "postgres", driver)
if err != nil {
fmt.Println("Error during migration: ", err)
os.Exit(1)
}
migration.Up()
err = db.Close()
if err != nil {
fmt.Println("Error closing connection after migration: ", err)
os.Exit(1)
}
dbConn, err = pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
fmt.Println("Error connecting to the database: ", err)
os.Exit(1)
}
}
func main() {
defer dbConn.Close(context.Background())
token := os.Getenv("BOT_TOKEN")
discord, err := discordgo.New("Bot " + token)
if err != nil {
fmt.Println("Error creating Discord session: ", err)
os.Exit(1)
}
defer discord.Close()
discord.AddHandler(messageCreate)
err = discord.Open()
if err != nil {
fmt.Println("Error opening connection: ", err)
os.Exit(1)
}
fmt.Println("Bot is now running. Press CTRL-C to exit.")
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-sc
}
func messageCreate(session *discordgo.Session, m *discordgo.MessageCreate) {
if m.Author.ID == session.State.User.ID {
return
}
messageSender := &discordMessageSender{session, m}
messageParser := &discordMessageParser{discordMessage: m}
db := &postgresDataLayer{dbConn}
bot := catanBot{messageSender, messageParser, db}
bot.handleCommand()
}