telegram-bot-api icon indicating copy to clipboard operation
telegram-bot-api copied to clipboard

Readme example for webhooks not working

Open fffilimonov opened this issue 2 years ago • 2 comments

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)

fffilimonov avatar May 02 '22 06:05 fffilimonov

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"
}

exitstop avatar Oct 19 '22 14:10 exitstop

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"))

bos-info avatar Nov 12 '22 16:11 bos-info