diff options
| author | Dmitry Ilvokhin <d@ilvokhin.com> | 2025-03-03 21:31:10 +0000 | 
|---|---|---|
| committer | Dmitry Ilvokhin <d@ilvokhin.com> | 2025-03-03 21:31:10 +0000 | 
| commit | 547a44a9fb502a308f596e6ffe1a90bd6c4607bc (patch) | |
| tree | ae20f6fbcf0689569bec5b6ae018a01271abdce1 | |
| parent | 96bcc15d6e3e820309c874fe39df11cb88b30af2 (diff) | |
| download | flatbot-547a44a9fb502a308f596e6ffe1a90bd6c4607bc.tar.gz flatbot-547a44a9fb502a308f596e6ffe1a90bd6c4607bc.tar.bz2 flatbot-547a44a9fb502a308f596e6ffe1a90bd6c4607bc.zip | |
Send message to Telegram
| -rw-r--r-- | flatbot.go | 13 | ||||
| -rw-r--r-- | messenger.go | 47 | 
2 files changed, 60 insertions, 0 deletions
| @@ -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) +} |