92 lines
1.8 KiB
Go
92 lines
1.8 KiB
Go
package alert
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"strconv"
|
|
"time"
|
|
|
|
"git.dev.m-and-m.ovh/mderasse/tesla/api"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
var apiClient *api.Client
|
|
var alert = 0
|
|
|
|
// Init will initialize telegram bot.
|
|
func Init(alertChan chan api.Availability) {
|
|
log.Info("Starting alert ticker")
|
|
|
|
var err error
|
|
apiClient, err = api.NewClient()
|
|
if err != nil {
|
|
log.Fatalf("Fail to instantiate the HTTP Client. Error: %s", err.Error())
|
|
}
|
|
|
|
priceAlertStr := os.Getenv("PRICE_ALERT")
|
|
if priceAlertStr != "" {
|
|
PriceAlert, err = strconv.ParseInt(priceAlertStr, 10, 64)
|
|
if err != nil {
|
|
log.Fatalf("invalid configuration. PRICE_ALERT environement variable should be an integer.")
|
|
}
|
|
}
|
|
|
|
// define an interval and the ticker for this interval
|
|
interval := time.Duration(2) * time.Second
|
|
// create a new Ticker
|
|
tk := time.NewTicker(interval)
|
|
|
|
resetAlert := 0
|
|
for range tk.C {
|
|
if alert > 10 {
|
|
alert = 0
|
|
resetAlert = 10
|
|
continue
|
|
}
|
|
|
|
if resetAlert != 0 {
|
|
resetAlert--
|
|
continue
|
|
}
|
|
|
|
checkPrice(alertChan)
|
|
}
|
|
}
|
|
|
|
func checkPrice(alertChan chan api.Availability) {
|
|
log.Info("Ticker - Checking price")
|
|
|
|
availabilities, err := apiClient.GetAvailabilities(context.Background(), &api.AvailabilityParams{
|
|
Query: carFilter,
|
|
Count: 100,
|
|
})
|
|
if err != nil {
|
|
log.Warnf("Fail to contact API. Error: %s", err.Error())
|
|
return
|
|
}
|
|
|
|
StdAlert := false
|
|
LrAlert := false
|
|
for _, availability := range availabilities.Results {
|
|
|
|
if availability.IsDemo && availability.Odometer > 100 {
|
|
continue
|
|
}
|
|
|
|
if !StdAlert && availability.Price < 39000 && availability.Trim[0] == "SRRWD" {
|
|
log.Info("Launching an alert !")
|
|
alertChan <- availability
|
|
alert++
|
|
StdAlert = true
|
|
}
|
|
|
|
if !LrAlert && availability.Price < 47000 && availability.Trim[0] == "LRAWD" {
|
|
log.Info("Launching an alert !")
|
|
alertChan <- availability
|
|
alert++
|
|
LrAlert = true
|
|
}
|
|
}
|
|
}
|