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

1 comment / Add your comment below

  1. Amazing post!!
    I appreciate the fact that you have explained all the information in depth.
    Well researched & well-listed posts, especially those who didn’t know how to send a telegram alert message using Go, they will get support for sure. Keep focusing on such topics.
    Thanks for sharing such a valuable post.

Leave a Reply

Your email address will not be published. Required fields are marked *