go-telegram-bot-api / telegram-bot-api

Golang bindings for the Telegram Bot API
https://go-telegram-bot-api.dev
MIT License
5.7k stars 879 forks source link

Readme example for webhooks not working #546

Open fffilimonov opened 2 years ago

fffilimonov commented 2 years ago

cannot use "cert.pem" (constant of type string) as type tgbotapi.RequestFileData in argument to tgbotapi.NewWebhookWithCert: string does not implement tgbotapi.RequestFileData (missing NeedsUpload method)

exitstop commented 1 year ago

Working example

package main

import (
    "bufio"
    "fmt"
    "io"
    "log"
    "net/http"
    "os"
    "time"

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

// 1) openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3560 -subj "/O=Org\CN=192.168.0.100" -nodes
// 2) openssl req -new -x509 -sha256 -key key.pem -out cert.pem -days 3650
func main() {
    apiKey := "1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    bot, err := tgbotapi.NewBotAPI(apiKey)
    if err != nil {
        log.Fatal(err)
    }

    bot.Debug = true

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

    go http.ListenAndServeTLS("192.168.0.100:8443", "cert.pem", "key.pem", nil)
    time.Sleep(500 * time.Millisecond)

    certFile := Tg{
        FileName: "cert.pem",
    }

    wh, err := tgbotapi.NewWebhookWithCert("https://192.168.0.100:8443/"+bot.Token, certFile)
    if err != nil {
        log.Fatal(err)
    }

    _, 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)

    for update := range updates {
        fmt.Println(update)
    }
}

type Tg struct {
    FileName string
}

func (t Tg) NeedsUpload() bool {
    return true
}

func (t Tg) UploadData() (name string, ioOut io.Reader, err error) {
    file, err := os.Open(t.FileName)
    return t.FileName, bufio.NewReader(file), err
}

func (t Tg) SendData() string {
    return "ok"
}
bos-info commented 1 year ago

i think we have more simple solution, just add FilePath before filename wh, err := tgbotapi.NewWebhookWithCert("https://example.com:8443/"+bot.Token, tgbotapi.FilePath("cert.pem"))