package main import ( "fmt" "strings" "time" "github.com/go-errors/errors" tele "gopkg.in/telebot.v3" "git.gensokyo.cafe/kkyy/tgbot_misaka_5882f7/stats" ) func isFromAdmin(upd tele.Update) bool { if upd.Message == nil || upd.Message.Sender == nil { return false } _, ok := config.AdminUIDs[upd.Message.Sender.ID] return ok } func initBot() (*tele.Bot, error) { pref := tele.Settings{ Token: config.TGBotToken, Poller: &tele.LongPoller{Timeout: 15 * time.Second}, } b, err := tele.NewBot(pref) if err != nil { return nil, errors.Wrap(err, 0) } // command routing b.Handle("/start", handleStartCmd) b.Handle("/traffic", handleTrafficCmd) return b, nil } func handleStartCmd(c tele.Context) error { upd := c.Update() if !isFromAdmin(upd) { return c.Send("Hello, stranger :)") } return c.Send("Hi :)") } func handleTrafficCmd(c tele.Context) error { upd := c.Update() if !isFromAdmin(upd) { return nil } dailyTraffic, err := stats.VnstatDailyTraffic(config.WatchedInterface) if err != nil { _ = c.Reply("im die, thank you forever") return err } monthlyTraffic, err := stats.VnstatMonthlyTraffic(config.WatchedInterface) if err != nil { _ = c.Reply("im die, thank you forever") return err } var responseParts = []string{"*Traffic Usage Summaries*\n"} // Yesterday's traffic if present if len(dailyTraffic) > 1 { row := dailyTraffic[len(dailyTraffic)-2] day := fmt.Sprintf("%d-%02d-%02d", row.Date.Year, row.Date.Month, row.Date.Day) responseParts = append( responseParts, fmt.Sprintf("Yesterday (%s):` %s`", day, fmtTraffic(row)), ) } // Today's traffic if present if len(dailyTraffic) > 0 { row := dailyTraffic[len(dailyTraffic)-1] responseParts = append( responseParts, fmt.Sprintf("Today so far:` %s`\n", fmtTraffic(row)), ) } // Last month's traffic, if present if len(monthlyTraffic) > 1 { row := monthlyTraffic[len(monthlyTraffic)-2] month := fmt.Sprintf("%d-%02d", row.Date.Year, row.Date.Month) responseParts = append( responseParts, fmt.Sprintf("Last month (%s):` %s`", month, fmtTraffic(row)), ) } // This month's traffic, if present if len(monthlyTraffic) > 0 { row := monthlyTraffic[len(monthlyTraffic)-1] responseParts = append( responseParts, fmt.Sprintf("This month so far:` %s`", fmtTraffic(row)), ) } var respText string if len(responseParts) == 1 { respText = "No traffic data available." } else { respText = strings.Join(responseParts, "\n") } return c.Reply(respText, &tele.SendOptions{ParseMode: tele.ModeMarkdown}) } func fmtTraffic(r stats.VnstatTrafficRecord) string { biggest := r.Rx if r.Tx > biggest { biggest = r.Tx } return fmt.Sprintf("%.2f GiB", float64(biggest)/1024/1024/1024) }