summaryrefslogtreecommitdiffstats
path: root/main.go
blob: 36aecab68b1324039f3fab8704a67e305f413656 (plain)
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
// Command cepis-telegram is the official Telegram bot for https://cep.is.
//
// It answers a bare CEP in a private chat, "/cep <cep>" in groups and channels,
// and inline queries anywhere. Updates arrive by long polling, so the process
// needs no inbound port, no public hostname and no webhook secret.
//
// Configuration is environment-only; see the config package.
package main

import (
	"context"
	"errors"
	"log/slog"
	"os"
	"os/signal"
	"syscall"

	"cep.is/telegrambot/internal/app"
	"cep.is/telegrambot/internal/config"
)

func main() {
	if err := run(); err != nil {
		slog.New(slog.NewJSONHandler(os.Stdout, nil)).Error("fatal", slog.String("error", err.Error()))
		os.Exit(1)
	}
}

func run() error {
	cfg, err := config.Load()
	if err != nil {
		if errors.Is(err, config.ErrMissingToken) {
			return errors.New(config.EnvToken + " is required: create a bot with @BotFather and pass its token in the environment")
		}
		return err
	}

	logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: cfg.LogLevel}))
	slog.SetDefault(logger)
	logger.Info("configuration loaded", slog.Any("config", cfg))

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	application, err := app.New(ctx, cfg, logger)
	if err != nil {
		return err
	}
	return application.Run(ctx)
}