重构(service/binance.go & service/guard.go): 优化时区设置,增强代码健壮性。

This commit is contained in:
wood chen 2024-09-18 02:04:22 +08:00
parent d7407628b3
commit d0af4542f7
2 changed files with 17 additions and 12 deletions

View File

@ -28,6 +28,9 @@ func init() {
chatID = mustParseInt64(os.Getenv("CHAT_ID")) chatID = mustParseInt64(os.Getenv("CHAT_ID"))
symbols = strings.Split(os.Getenv("SYMBOLS"), ",") symbols = strings.Split(os.Getenv("SYMBOLS"), ",")
// 初始化 singaporeTZ
singaporeTZ = time.FixedZone("Asia/Singapore", 8*60*60) // UTC+8
bot, err = tgbotapi.NewBotAPI(botToken) bot, err = tgbotapi.NewBotAPI(botToken)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
@ -95,7 +98,13 @@ func formatChange(changePercent float64) string {
} }
func sendPriceUpdate() { func sendPriceUpdate() {
now := time.Now().In(singaporeTZ) var now time.Time
if singaporeTZ != nil {
now = time.Now().In(singaporeTZ)
} else {
now = time.Now().UTC()
log.Println("Warning: singaporeTZ is nil, using UTC")
}
message := fmt.Sprintf("市场更新 - %s (SGT)\n\n", now.Format("2006-01-02 15:04:05")) message := fmt.Sprintf("市场更新 - %s (SGT)\n\n", now.Format("2006-01-02 15:04:05"))
for _, symbol := range symbols { for _, symbol := range symbols {
@ -132,16 +141,12 @@ func sendPriceUpdate() {
} }
func RunBinance() { func RunBinance() {
log.Println("Sending initial price update...") log.Println("Starting Binance service...")
sendPriceUpdate()
ticker := time.NewTicker(1 * time.Hour)
defer ticker.Stop()
for { for {
select { log.Println("Sending price update...")
case <-ticker.C:
sendPriceUpdate() sendPriceUpdate()
}
log.Println("Waiting for next update...")
time.Sleep(1 * time.Hour)
} }
} }

View File

@ -145,7 +145,7 @@ func StartBot() error {
log.Printf("Authorized on account %s", bot.Self.UserName) log.Printf("Authorized on account %s", bot.Self.UserName)
err = core.RegisterCommands(bot, adminID) err = core.RegisterCommands(bot, 0)
if err != nil { if err != nil {
return fmt.Errorf("error registering commands: %w", err) return fmt.Errorf("error registering commands: %w", err)
} }