telegram-bot-send-message/main.go

80 lines
1.3 KiB
Go

package main
import (
"fmt"
"log"
"os"
"strconv"
"time"
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")
var err error
config.ChatId, err = strconv.ParseInt(os.Getenv("TELEGRAM_CHAT_ID"), 10, 64)
if err != nil {
return config, err
}
return config, nil
}
const DEADLINE = 6000
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]
}
delay := 1
original_time := time.Now()
for true {
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)
if _, err := bot.Send(msg); err != nil {
log.Println(err)
delay = delay * 2
if delay > DEADLINE {
break
}
time.Sleep(time.Second * time.Duration(delay))
continue
} else {
break
}
}
}