Go语言 telegram-bot-API/v5 SetWebhook函数未定义

ezykj2lf  于 2023-09-28  发布在  Go
关注(0)|答案(1)|浏览(84)

在官方文档中,有以下使用webhook构建tg bot的示例代码:

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)

    wh, _ := tgbotapi.NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem")

    _, err = bot.SetWebhook(wh)
    if err != nil {
        log.Fatal(err)
    }

    info, err := bot.GetWebhookInfo()
    if err != nil {
        log.Fatal(err)
    }

    if info.LastErrorDate != 0 {
        log.Printf("Telegram callback failed: %s", info.LastErrorMessage)
    }

    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\n", update)
    }
}

我正在遵循这个例子,但是遇到了使用bot.SetWebhook(wh)的问题,它显示

bot.SetWebhhook() undefined (type *tgbotapi.BotAPI has no field or method SetWebhook)

这个包是版本问题还是环境设置问题?还是别的什么
我不知道该怎么办才来找你帮忙
Thanks in advance

bttbmeg0

bttbmeg01#

你提供的例子是旧的,不再有SetWebhhook方法。首先安装软件包(如果没有安装,请安装最新版本):

go get -u github.com/go-telegram-bot-api/telegram-bot-api/v5

下面是一个包含webhooks的工作示例:

package main

import (
    "log"
    "net/http"

    "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)

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)

    wh, _ := tgbotapi.NewWebhookWithCert("https://www.example.com:8443/"+bot.Token, "cert.pem")

    _, err = bot.Request(wh)
    if err != nil {
        log.Fatal(err)
    }

    info, err := bot.GetWebhookInfo()
    if err != nil {
        log.Fatal(err)
    }

    if info.LastErrorDate != 0 {
        log.Printf("Telegram callback failed: %s", info.LastErrorMessage)
    }

    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\n", update)
    }
}

相关问题