dpj997991 2017-11-10 17:55
浏览 163
已采纳

使用Heroku上的Go,GoLang的Telegram Bot API Webhooks

I use go-telegram-bot-api for building a Telegram Bot and deploying it on Heroku.

I need to set Webhooks as I used to do in Python like in this Python case.

Can't understand how to set Webhooks in go-telegram-bot-api without providing certificate files.

The main example contains such lines:

If you need to use webhooks (if you wish to run on Google App Engine), you may use a slightly different method.

package main

import (
    "gopkg.in/telegram-bot-api.v4"
    "log"
    "net/http"
)

func main() {
    bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
    if err != nil {
        log.Fatal(err)
    }

    bot.Debug = true

    log.Printf("Authorized on account %s", bot.Self.UserName)

    _, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem"))
    if err != nil {
        log.Fatal(err)
    }

    updates := bot.ListenForWebhook("/" + bot.Token)
    go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)

    for update := range updates {
        log.Printf("%+v
", update)
    }
}

But using Heroku for deploying how could I listen to Webhooks without providing pem certificate files?

  • 写回答

2条回答 默认 最新

  • doumen5895 2017-11-17 23:00
    关注

    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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动