How to send a Telegram alert message using Go

Here’s a simple example of how to send a message from Go via Telegram:

package main

import (
"bytes"
"fmt"
"net/http"
"encoding/json"
)

func send(text string, bot string, chat_id string) {

request_url := "https://api.telegram.org/" + bot + "/sendMessage"

client := &http.Client{}

values := map[string]string{"text": text, "chat_id": chat_id }
json_paramaters, _ := json.Marshal(values)

req, _:= http.NewRequest("POST", request_url, bytes.NewBuffer(json_paramaters))
req.Header.Set("Content-Type", "application/json")

res, err := client.Do(req)

if(err != nil){
fmt.Println(err)
} else {
fmt.Println(res.Status)
defer res.Body.Close()
}

}

func main() {

send("hello telegram", "bot<TOKEN>", "<CHAT_ID>")

} // main
[j@us:1~]$ go run zsend.go
200 OK
[j@us:1 ~]$

For testing it might be easier to use curl:

curl -v -X POST -H 'Content-Type: application/json' -d '{"chat_id": "<CHAT_ID>", "text": "hello telegram"}' https://api.telegram.org/bot<TOKEN>/sendMessage

Leave a Reply

Your email address will not be published.