-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
74 lines (67 loc) · 2.08 KB
/
config.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
package tbb
import (
"gopkg.in/yaml.v3"
"os"
)
const (
defaultSessionTimout = 15 // Default bot session timeout of 15 minutes of inactivity
)
type Config struct {
Admin struct {
BotToken string `yaml:"botToken"` // Telegram bot token for an admin bot to use when sending messages
ChatIDs []int64 `yaml:"chatIDs"` // Telegram chat IDs of admins
} `yaml:"admin"`
AllowedChatIDs []int64 `yaml:"allowedChatIDs"` // If set, only the specified chatIDs are allowed to use the bot. If not set or empty, all chat ids are allowed to use the bot.
Database struct {
Type string `yaml:"type"` // one of sqlite, mysql, postgres
DSN string `yaml:"dsn"` // in the case of mysql or postgres
Filename string `yaml:"filename"` // in the case of sqlite
} `yaml:"database"`
Debug bool `yaml:"debug"`
BotSessionTimeout int `yaml:"botSessionTimeout"` // Timeout in minutes, after which the bot instance will be deleted to save memory. Defaults to 15 minutes.
LogLevel string `yaml:"logLevel"`
Telegram struct {
BotToken string `yaml:"botToken"`
} `yaml:"telegram"`
CustomData any `yaml:"customData"`
}
// LoadConfig returns the yaml config with the given name
func LoadConfig(filename string) *Config {
return loadConfig(filename)
}
// LoadCustomConfig returns the config but also takes your custom struct for the "customData" into account.
func LoadCustomConfig[T any](filename string) *Config {
cfg := loadConfig(filename)
out, err := yaml.Marshal(&cfg.CustomData)
if err != nil {
panic(err)
}
var custom T
err = yaml.Unmarshal(out, &custom)
if err != nil {
panic(err)
}
cfg.CustomData = custom
return cfg
}
func loadConfig(filename string) *Config {
var cfg Config
data, err := os.ReadFile(filename)
if err != nil {
panic(err)
}
err = yaml.Unmarshal(data, &cfg)
if err != nil {
panic(err)
}
if cfg.Telegram.BotToken == "" {
panic("missing telegram bot token")
}
if cfg.Database.Filename == "" {
panic("missing database")
}
if cfg.BotSessionTimeout == 0 {
cfg.BotSessionTimeout = defaultSessionTimout
}
return &cfg
}