Implement SendTextToTelegram function

This commit is contained in:
ekzyis 2023-04-28 17:34:26 +02:00
parent 165d074467
commit 6014ccedc3
6 changed files with 62 additions and 0 deletions

2
.env.template Normal file
View File

@ -0,0 +1,2 @@
TELEGRAM_BOT_TOKEN=
TELEGRAM_CHAT_ID=

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.env

8
go.mod Normal file
View File

@ -0,0 +1,8 @@
module gitlab.com/ekzyis/stackernews_rss-to-tg
go 1.20
require (
github.com/joho/godotenv v1.5.1 // indirect
github.com/namsral/flag v1.7.4-pre // indirect
)

4
go.sum Normal file
View File

@ -0,0 +1,4 @@
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/namsral/flag v1.7.4-pre h1:b2ScHhoCUkbsq0d2C15Mv+VU8bl8hAXV8arnWiOHNZs=
github.com/namsral/flag v1.7.4-pre/go.mod h1:OXldTctbM6SWH1K899kPZcf65KxJiD7MsceFUpB5yDo=

4
main.go Normal file
View File

@ -0,0 +1,4 @@
package main
func main() {
}

43
tg.go Normal file
View File

@ -0,0 +1,43 @@
package main
import (
"fmt"
"log"
"net/http"
"github.com/joho/godotenv"
"github.com/namsral/flag"
)
var (
ChatId int
BotToken string
)
func init() {
err := godotenv.Load()
if err != nil {
log.Fatal("error loading .env file")
}
flag.IntVar(&ChatId, "TELEGRAM_CHAT_ID", 0, "Chat id of telegram channel")
flag.StringVar(&BotToken, "TELEGRAM_BOT_TOKEN", "", "Telegram bot token")
flag.Parse()
if ChatId == 0 {
log.Fatal("TELEGRAM_CHAT_ID not set")
}
if BotToken == "" {
log.Fatal("TELEGRAM_BOT_TOKEN not set")
}
}
func SendTextToTelegram(text string) {
url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage?chat_id=%d&text=%s", BotToken, ChatId, text)
resp, err := http.Get(url)
if err != nil {
err = fmt.Errorf("error during GET %s: %w", url, err)
log.Println(err)
return
}
defer resp.Body.Close()
log.Printf("GET %s: %d\n", url, resp.StatusCode)
}