This page looks best with JavaScript enabled

Sending messages through Telegram in Go

 ·  🎃 kr0m

Sending messages through Telegram is very useful, especially when programming check or backup scripts. This way, we can be notified about certain alarms or errors.

In this tutorial, we will see a simple use case:

vi telegram.go

package main

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

func sendTelegram(text string) {
    bot := "BOT_TOKEN"
    chatId := "CHAT_ID"
    requestUrl := "https://api.telegram.org/" + bot + "/sendMessage"
    client := &http.Client{}
    values := map[string]string{"text": text, "chat_id": chatId }
    jsonParamaters, _ := json.Marshal(values)
    req, _:= http.NewRequest("POST", requestUrl, bytes.NewBuffer(jsonParamaters))
    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() {
    sendTelegram("AlfaExploit test")
}

Execute the program:

go run telegram.go

We should receive the message on Telegram.

If you liked the article, you can treat me to a RedBull here