public-ip-tracker/tracker/bot/bot.go
Melora Hugues 3948c8e7b4 Add publig IP getter
Ref #3

This commit uses a GET query to ifconfig.me in order to get the current
public IP. It also modifies the initialization message to send the
current public IP to the Telegram channel instead of a simple message.
2023-01-27 18:01:37 +01:00

45 lines
1.1 KiB
Go

package bot
import (
"context"
"fmt"
"time"
"git.faercol.me/faercol/public-ip-tracker/tracker/config"
"git.faercol.me/faercol/public-ip-tracker/tracker/ip"
"github.com/ahugues/go-telegram-api/bot"
)
type Notifier struct {
ctx context.Context
cancel context.CancelFunc
tgBot *bot.ConcreteBot
notifChannel int64
ipGetter *ip.IPGetter
}
func (n *Notifier) SendInitMessage() error {
publicIP, err := n.ipGetter.GetCurrentPublicIP(n.ctx)
if err != nil {
return fmt.Errorf("failed to get current public IP: %w", err)
}
initMsg := fmt.Sprintf("Public IP tracker initialized at %v, public IP is %s", time.Now(), publicIP)
if err := n.tgBot.SendMessage(n.ctx, n.notifChannel, initMsg); err != nil {
return fmt.Errorf("failed to send initialization message: %w", err)
}
return nil
}
func New(ctx context.Context, config *config.Config) *Notifier {
subCtx, cancel := context.WithCancel(ctx)
tgBot := bot.New(config.Telegram.Token)
return &Notifier{
ctx: subCtx,
cancel: cancel,
tgBot: tgBot,
notifChannel: config.Telegram.ChannelID,
ipGetter: ip.New(),
}
}