StatusCheck/main.go

110 lines
2.3 KiB
Go
Raw Normal View History

2024-07-18 04:36:23 +02:00
package main
import (
"context"
"fmt"
"log"
"net"
"strconv"
"time"
"github.com/BurntSushi/toml"
"github.com/diamondburned/arikawa/v3/api"
"github.com/diamondburned/arikawa/v3/discord"
"github.com/diamondburned/arikawa/v3/gateway"
"github.com/diamondburned/arikawa/v3/state"
)
type Config struct {
Bot BotConfig `toml:"Bot"`
Services []Service `toml:"Service"`
}
type BotConfig struct {
Token string `toml:"token"`
}
type Service struct {
Name string `toml:"name"`
ChannelID string `toml:"channelID"`
IP string `toml:"ip"`
Port int `toml:"port"`
Time int `toml:"time"`
UpStatus string `toml:"upStatus"`
DownStatus string `toml:"downStatus"`
}
var config Config
func main() {
if _, err := toml.DecodeFile("config.toml", &config); err != nil {
log.Fatalf("Error loading config file: %v", err)
}
s := state.New("Bot " + config.Bot.Token)
s.AddIntents(gateway.IntentGuildMessages)
s.AddIntents(gateway.IntentDirectMessages)
if err := s.Open(context.Background()); err != nil {
log.Fatalln("Failed to connect:", err)
}
defer s.Close()
u, err := s.Me()
if err != nil {
log.Fatalln("Failed to get myself:", err)
}
fmt.Printf("Bot (%s) is now running. Press CTRL+C to exit.\n", u.Username)
for _, service := range config.Services {
go monitorService(s, service)
}
select {}
}
func monitorService(s *state.State, service Service) {
prevStatus := "INIT"
i, _ := strconv.ParseInt(service.ChannelID, 10, 64)
channelID := discord.ChannelID(i)
for {
status := checkService(service.IP, service.Port)
log.Printf("Service %s status: %s", service.Name, status)
var statusMessage string
if status == "UP" {
statusMessage = service.UpStatus
} else {
statusMessage = service.DownStatus
}
if prevStatus != status {
newName := fmt.Sprintf("%s%s", service.Name, statusMessage)
log.Printf("Attempting to change channel name to: %s", newName)
err := s.ModifyChannel(channelID, api.ModifyChannelData{
Name: newName,
})
if err == nil {
prevStatus = status
} else {
log.Fatalln(err)
}
}
time.Sleep(time.Duration(service.Time) * time.Second)
}
}
func checkService(ip string, port int) string {
timeout := 2 * time.Second
conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", ip, port), timeout)
if err != nil {
return "DOWN"
}
conn.Close()
return "UP"
}