Following this https://devcenter.heroku.com/articles/getting-started-with-go to get the starter code.
initTelegram()
and webhookHandler()
are functions to study.
Once code is deployed to Heroku, run:
heroku logs --tail -a <YOUR-APP-NAME>
send some messages to the bot, you should see messages logged.
UPDATE 1
Check your app URL is the same as baseURL variable in your code -- run heroku info -a <YOUR-APP-NAME>
-- your URL should be equal to what Web URL is.
UPDATE 2
In order to check your Telegram API Webhooks response ping this address in your browser: https://api.telegram.org/bot<YOUR BOT TOKEN GOES HERE>/getWebhookInfo
where you should concatenate string bot
and your actual Telegram Bot Token in that address string.
Optionally if you run your code not on Heroku, running curl
from terminal could be an option according to Official Telegram API Reference:
$ curl -F "url=https://your.domain.or.ip.com" -F "certificate=@/etc/ssl/certs/bot.pem" https://api.telegram.org/bot<YOUR BOT TOKEN GOES HERE>/setWebhook
THE CODE:
package main
import (
"encoding/json"
"io"
"io/ioutil"
"log"
"os"
"github.com/gin-gonic/gin"
"gopkg.in/telegram-bot-api.v4"
_ "github.com/heroku/x/hmetrics/onload"
_ "github.com/lib/pq"
)
var (
bot *tgbotapi.BotAPI
botToken = "<YOUR BOT TOKEN GOES HERE>"
baseURL = "https://<YOUR-APP-NAME>.herokuapp.com/"
)
func initTelegram() {
var err error
bot, err = tgbotapi.NewBotAPI(botToken)
if err != nil {
log.Println(err)
return
}
// this perhaps should be conditional on GetWebhookInfo()
// only set webhook if it is not set properly
url := baseURL + bot.Token
_, err = bot.SetWebhook(tgbotapi.NewWebhook(url))
if err != nil {
log.Println(err)
}
}
func webhookHandler(c *gin.Context) {
defer c.Request.Body.Close()
bytes, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
log.Println(err)
return
}
var update tgbotapi.Update
err = json.Unmarshal(bytes, &update)
if err != nil {
log.Println(err)
return
}
// to monitor changes run: heroku logs --tail
log.Printf("From: %+v Text: %+v
", update.Message.From, update.Message.Text)
}
func main() {
port := os.Getenv("PORT")
if port == "" {
log.Fatal("$PORT must be set")
}
// gin router
router := gin.New()
router.Use(gin.Logger())
// telegram
initTelegram()
router.POST("/" + bot.Token, webhookHandler)
err := router.Run(":" + port)
if err != nil {
log.Println(err)
}
}
Good luck and have fun!