summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--flatbot.go13
-rw-r--r--messenger.go47
2 files changed, 60 insertions, 0 deletions
diff --git a/flatbot.go b/flatbot.go
index 3cb052f..fc565f7 100644
--- a/flatbot.go
+++ b/flatbot.go
@@ -5,6 +5,7 @@ import (
"io"
"log"
"net/http"
+ "os"
)
func main() {
@@ -22,6 +23,18 @@ func main() {
log.Fatal(err)
}
flats = removeAlreadySent(flats, sent)
+ m := messenger{
+ Token: os.Getenv("FLATBOT_TELEGRAM_BOT_API_TOKEN"),
+ ChatID: os.Getenv("FLATBOT_TELEGRAM_CHANNEL_ID"),
+ }
+ for _, f := range flats {
+ err = m.Send(f)
+ if err != nil {
+ // TODO: what to do with it?
+ log.Print(err)
+ }
+ sent = append(sent, f)
+ }
fmt.Println(flats)
writeSent(flats, "/tmp/sent.json")
}
diff --git a/messenger.go b/messenger.go
new file mode 100644
index 0000000..127ebc2
--- /dev/null
+++ b/messenger.go
@@ -0,0 +1,47 @@
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+)
+
+type messenger struct {
+ Token string
+ ChatID string
+}
+
+func (m *messenger) Send(f flat) error {
+ text := fmt.Sprintf("%v\n%v", f.Price, f.URL())
+ data := url.Values{"chat_id": {m.ChatID}, "text": {text}}
+ resp, err := http.PostForm(m.makeURL(), data)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return err
+ }
+ type errorResponse struct {
+ ErrorCode int `json:"error_code"`
+ Description string `json:"description"`
+ }
+ errorResp := errorResponse{}
+ if err := json.Unmarshal(body, &errorResp); err != nil {
+ return err
+ }
+ return fmt.Errorf("Error code: %v, description: %v",
+ errorResp.ErrorCode, errorResp.Description)
+ }
+ return nil
+}
+
+func (m *messenger) makeURL() string {
+ return fmt.Sprintf(
+ "https://api.telegram.org/bot%v/sendMessage",
+ m.Token)
+}