Reputation: 709
I work with telegram using github.com/go-telegram-bot-api/telegram-bot-api Later I uploaded photos using external links: Simplified code is like this:
url := `http://path-to-image/img.jpg`
msg := tgbotapi.NewPhotoUpload(groupID, nil)
msg.FileID = url
msg.Caption = "New photo"
bot.Send(msg)
But now, my photos are available only in the closed local network. Links like http://example.loc/img.jpg obviously do not work. So, I download a file and then try to upload it from disk or from memory. There are lots of examples here https://github.com/go-telegram-bot-api/telegram-bot-api/blob/master/bot_test.go But no one works. I tried all the examples and even more, but I always get various errors:
And so on.
Does anybody know how to upload photo from disk or from memory (even better). Thanks in advance.
Upvotes: 3
Views: 8243
Reputation: 51
bot, err := tgbotapi.NewBotAPI(telegram_bot_token)
if err != nil {
fmt.Println(err)
}
file, _ := os.Open("image.jpg")
reader := tgbotapi.FileReader{Name: "image.jpg", Reader: file}
photo := tgbotapi.NewPhoto(telegram_group_id, reader)
photo.Caption = "test caption"
_, err = bot.Send(photo)
if err != nil {
fmt.Println(err)
}
Upvotes: 1
Reputation: 2393
One way to upload a picture from local disk is to read the file, then passing the byte array to a FileBytes, wrap it with a Chattable like PhotoConfig and send it through bot.send
:
photoBytes, err := ioutil.ReadFile("/your/local/path/to/picture.png")
if err != nil {
panic(err)
}
photoFileBytes := tgbotapi.FileBytes{
Name: "picture",
Bytes: photoBytes,
}
chatID := 12345678
message, err := bot.Send(tgbotapi.NewPhotoUpload(int64(chatID), photoFileBytes))
Here tgbotapi.NewPhotoUpload()
creates a PhotoConfig for us.
Upvotes: 4