telegram-bot-send-message/main.go

68 lines
1.1 KiB
Go
Raw Normal View History

2022-09-10 00:45:41 +00:00
package main
import (
"encoding/json"
"io"
"log"
"os"
"path"
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{}
homeDir, err := os.UserHomeDir()
if err != nil {
return config, err
}
pathName := path.Join(homeDir, ".config/telegram-bot-send-message.json")
file, err := os.Open(pathName)
if err != nil {
return config, err
}
configBytes, err := io.ReadAll(file)
if err != nil {
return config, err
}
err = json.Unmarshal(configBytes, &config)
if err != nil {
return config, err
}
return config, nil
}
func main() {
config, err := readConfig()
if err != nil {
panic(err)
}
bot, err := tgbotapi.NewBotAPI(config.Token)
if err != nil {
panic(err)
}
text := "No se especificó un mensaje."
if len(os.Args) > 1 {
text = os.Args[1]
}
for true {
msg := tgbotapi.NewMessage(config.ChatId, text)
if _, err := bot.Send(msg); err != nil {
log.Println(err)
} else {
break
}
}
}