Search code examples
gotelegramtelegram-bot

Go Telegram Bot API upload photo from local file


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:

  • Bad Request: there is no photo in the request
  • Bad Request: host is invalid
  • Bad Request: URL host is empty
  • Bad Request: unsupported URL protocol

And so on.

Does anybody know how to upload photo from disk or from memory (even better). Thanks in advance.


Solution

  • 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.