telegram-bot-send-message/main.go

80 lines
1.3 KiB
Go
Raw Normal View History

2022-09-10 00:45:41 +00:00
package main
import (
2022-09-18 12:41:32 +00:00
"fmt"
2022-09-10 00:45:41 +00:00
"log"
"os"
"strconv"
2022-09-18 12:41:32 +00:00
"time"
2022-09-10 00:45:41 +00:00
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
type Config struct {
Token string `json:"token"`
ChatId int64 `json:"chat_id"`
}
func readConfig() (Config, error) {
config := Config{}
config.Token = os.Getenv("TELEGRAM_BOT_TOKEN")
2022-09-10 00:45:41 +00:00
var err error
config.ChatId, err = strconv.ParseInt(os.Getenv("TELEGRAM_CHAT_ID"), 10, 64)
2022-09-10 00:45:41 +00:00
if err != nil {
return config, err
}
2022-09-10 00:45:41 +00:00
return config, nil
}
2022-09-18 12:41:32 +00:00
const DEADLINE = 6000
2022-09-10 00:45:41 +00:00
func main() {
config, err := readConfig()
if err != nil {
panic(err)
}
text := "No se especificó un mensaje."
if len(os.Args) > 1 {
text = os.Args[1]
}
2022-09-18 12:41:32 +00:00
delay := 1
original_time := time.Now()
2022-09-10 00:45:41 +00:00
for true {
2022-09-18 12:41:32 +00:00
bot, err := tgbotapi.NewBotAPI(config.Token)
if err != nil {
log.Println(err)
delay = delay * 2
if delay > DEADLINE {
break
}
time.Sleep(time.Second * time.Duration(delay))
continue
}
timestamp := ""
if delay > 1 {
timestamp = fmt.Sprintf("[%s] ", original_time)
}
msg := tgbotapi.NewMessage(config.ChatId, timestamp+text)
2022-09-10 00:45:41 +00:00
if _, err := bot.Send(msg); err != nil {
log.Println(err)
2022-09-18 12:41:32 +00:00
delay = delay * 2
if delay > DEADLINE {
break
}
time.Sleep(time.Second * time.Duration(delay))
continue
2022-09-10 00:45:41 +00:00
} else {
break
}
}
}