feat(bot, configs): add support thumb to video, audio, documents

pull/228/head
jmen 6 years ago
parent ec221ba9ea
commit 1eeb287625
  1. 134
      bot.go
  2. 2
      bot_test.go
  3. 17
      configs.go
  4. 2
      helpers.go
  5. BIN
      tests/gopher.png
  6. BIN
      tests/video.mp4
  7. BIN
      tests/videonote.mp4

134
bot.go

@ -9,6 +9,7 @@ import (
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"mime/multipart"
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
@ -25,8 +26,8 @@ type BotAPI struct {
Debug bool `json:"debug"` Debug bool `json:"debug"`
Buffer int `json:"buffer"` Buffer int `json:"buffer"`
Self User `json:"-"` Self User `json:"-"`
Client *http.Client `json:"-"` Client *http.Client `json:"-"`
shutdownChannel chan interface{} shutdownChannel chan interface{}
} }
@ -43,9 +44,9 @@ func NewBotAPI(token string) (*BotAPI, error) {
// It requires a token, provided by @BotFather on Telegram. // It requires a token, provided by @BotFather on Telegram.
func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) { func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
bot := &BotAPI{ bot := &BotAPI{
Token: token, Token: token,
Client: client, Client: client,
Buffer: 100, Buffer: 100,
shutdownChannel: make(chan interface{}), shutdownChannel: make(chan interface{}),
} }
@ -134,10 +135,85 @@ func (bot *BotAPI) makeMessageRequest(endpoint string, params url.Values) (Messa
// Requires the parameter to hold the file not be in the params. // Requires the parameter to hold the file not be in the params.
// File should be a string to a file path, a FileBytes struct, // File should be a string to a file path, a FileBytes struct,
// a FileReader struct, or a url.URL. // a FileReader struct, or a url.URL.
// func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}, thumb interface{}) (APIResponse, error) {
// Note that if your FileReader has a size set to -1, it will read if thumb != nil {
// the file into memory to calculate a size. buffer := bytes.Buffer{}
func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}) (APIResponse, error) {
writer := multipart.NewWriter(&buffer)
params["thumb"] = "attach://test"
for k, v := range params {
if writerErr := writer.WriteField(k, v); writerErr != nil {
return APIResponse{}, writerErr
}
}
// Method file
f := file.(FileReader)
formFile, formFileErr := writer.CreateFormFile(fieldname, f.Name)
if formFileErr != nil {
return APIResponse{}, formFileErr
}
if _, copyErr := io.Copy(formFile, f.Reader); copyErr != nil {
return APIResponse{}, copyErr
}
// Thumb file
tf := thumb.(FileReader)
formFile1, formFileErr := writer.CreateFormFile("test", tf.Name)
if formFileErr != nil {
return APIResponse{}, formFileErr
}
if _, copyErr := io.Copy(formFile1, tf.Reader); copyErr != nil {
return APIResponse{}, copyErr
}
if err := writer.Close(); err != nil {
fmt.Println(err)
}
// http
method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint)
req, err := http.NewRequest("POST", method, &buffer)
if err != nil {
return APIResponse{}, err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
res, err := bot.Client.Do(req)
if err != nil {
return APIResponse{}, err
}
defer res.Body.Close()
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return APIResponse{}, err
}
if bot.Debug {
log.Println(string(bytes))
}
fmt.Println("bytes -- ", string(bytes))
var apiResp APIResponse
err = json.Unmarshal(bytes, &apiResp)
if err != nil {
return APIResponse{}, err
}
if !apiResp.Ok {
return APIResponse{}, errors.New(apiResp.Description)
}
return apiResp, nil
}
ms := multipartstreamer.New() ms := multipartstreamer.New()
switch f := file.(type) { switch f := file.(type) {
@ -166,10 +242,8 @@ func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldna
if f.Size != -1 { if f.Size != -1 {
ms.WriteReader(fieldname, f.Name, f.Size, f.Reader) ms.WriteReader(fieldname, f.Name, f.Size, f.Reader)
break break
} }
data, err := ioutil.ReadAll(f.Reader) data, err := ioutil.ReadAll(f.Reader)
if err != nil { if err != nil {
return APIResponse{}, err return APIResponse{}, err
@ -211,7 +285,7 @@ func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldna
} }
var apiResp APIResponse var apiResp APIResponse
fmt.Println("bytes1 --- ", string(bytes))
err = json.Unmarshal(bytes, &apiResp) err = json.Unmarshal(bytes, &apiResp)
if err != nil { if err != nil {
return APIResponse{}, err return APIResponse{}, err
@ -267,9 +341,26 @@ func (bot *BotAPI) IsMessageToMe(message Message) bool {
// //
// It requires the Chattable to send. // It requires the Chattable to send.
func (bot *BotAPI) Send(c Chattable) (Message, error) { func (bot *BotAPI) Send(c Chattable) (Message, error) {
var thumb interface{}
switch c.(type) {
case AudioConfig:
if c.(AudioConfig).Thumb.Reader != nil {
thumb = c.(AudioConfig).Thumb
}
case VideoConfig:
if c.(VideoConfig).Thumb.Reader != nil {
thumb = c.(VideoConfig).Thumb
}
case DocumentConfig:
if c.(DocumentConfig).Thumb.Reader != nil {
thumb = c.(DocumentConfig).Thumb
}
}
switch c.(type) { switch c.(type) {
case Fileable: case Fileable:
return bot.sendFile(c.(Fileable)) return bot.sendFile(c.(Fileable), thumb)
default: default:
return bot.sendChattable(c) return bot.sendChattable(c)
} }
@ -302,15 +393,14 @@ func (bot *BotAPI) sendExisting(method string, config Fileable) (Message, error)
} }
// uploadAndSend will send a Message with a new file to Telegram. // uploadAndSend will send a Message with a new file to Telegram.
func (bot *BotAPI) uploadAndSend(method string, config Fileable) (Message, error) { func (bot *BotAPI) uploadAndSend(method string, config Fileable, thumb interface{}) (Message, error) {
params, err := config.params() params, err := config.params()
if err != nil { if err != nil {
return Message{}, err return Message{}, err
} }
file := config.getFile() file := config.getFile()
resp, err := bot.UploadFile(method, params, config.name(), file, thumb)
resp, err := bot.UploadFile(method, params, config.name(), file)
if err != nil { if err != nil {
return Message{}, err return Message{}, err
} }
@ -319,18 +409,16 @@ func (bot *BotAPI) uploadAndSend(method string, config Fileable) (Message, error
json.Unmarshal(resp.Result, &message) json.Unmarshal(resp.Result, &message)
bot.debugLog(method, nil, message) bot.debugLog(method, nil, message)
return message, nil return message, nil
} }
// sendFile determines if the file is using an existing file or uploading // sendFile determines if the file is using an existing file or uploading
// a new file, then sends it as needed. // a new file, then sends it as needed.
func (bot *BotAPI) sendFile(config Fileable) (Message, error) { func (bot *BotAPI) sendFile(config Fileable, thumb interface{}) (Message, error) {
if config.useExistingFile() { if config.useExistingFile() {
return bot.sendExisting(config.method(), config) return bot.sendExisting(config.method(), config)
} }
return bot.uploadAndSend(config.method(), config, thumb)
return bot.uploadAndSend(config.method(), config)
} }
// sendChattable sends a Chattable. // sendChattable sends a Chattable.
@ -457,7 +545,7 @@ func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) {
params["max_connections"] = strconv.Itoa(config.MaxConnections) params["max_connections"] = strconv.Itoa(config.MaxConnections)
} }
resp, err := bot.UploadFile("setWebhook", params, "certificate", config.Certificate) resp, err := bot.UploadFile("setWebhook", params, "certificate", config.Certificate, nil)
if err != nil { if err != nil {
return APIResponse{}, err return APIResponse{}, err
} }
@ -490,7 +578,7 @@ func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) (UpdatesChannel, error) {
return return
default: default:
} }
updates, err := bot.GetUpdates(config) updates, err := bot.GetUpdates(config)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
@ -952,7 +1040,7 @@ func (bot *BotAPI) SetChatPhoto(config SetChatPhotoConfig) (APIResponse, error)
file := config.getFile() file := config.getFile()
return bot.UploadFile(config.method(), params, config.name(), file) return bot.UploadFile(config.method(), params, config.name(), file, nil)
} }
// DeleteChatPhoto delete photo of chat. // DeleteChatPhoto delete photo of chat.

@ -8,7 +8,7 @@ import (
"testing" "testing"
"time" "time"
"github.com/go-telegram-bot-api/telegram-bot-api" tgbotapi "."
) )
const ( const (

@ -2,6 +2,7 @@ package tgbotapi
import ( import (
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"net/url" "net/url"
"strconv" "strconv"
@ -127,7 +128,6 @@ func (file BaseFile) params() (map[string]string, error) {
if err != nil { if err != nil {
return params, err return params, err
} }
params["reply_markup"] = string(data) params["reply_markup"] = string(data)
} }
@ -297,6 +297,7 @@ type AudioConfig struct {
Duration int Duration int
Performer string Performer string
Title string Title string
Thumb FileReader
} }
// values returns a url.Values representation of AudioConfig. // values returns a url.Values representation of AudioConfig.
@ -366,6 +367,7 @@ type DocumentConfig struct {
BaseFile BaseFile
Caption string Caption string
ParseMode string ParseMode string
Thumb FileReader
} }
// values returns a url.Values representation of DocumentConfig. // values returns a url.Values representation of DocumentConfig.
@ -447,9 +449,11 @@ func (config StickerConfig) method() string {
// VideoConfig contains information about a SendVideo request. // VideoConfig contains information about a SendVideo request.
type VideoConfig struct { type VideoConfig struct {
BaseFile BaseFile
Duration int Duration int
Caption string Caption string
ParseMode string ParseMode string
Thumb FileReader
SupportsStreaming bool
} }
// values returns a url.Values representation of VideoConfig. // values returns a url.Values representation of VideoConfig.
@ -458,7 +462,7 @@ func (config VideoConfig) values() (url.Values, error) {
if err != nil { if err != nil {
return v, err return v, err
} }
fmt.Println()
v.Add(config.name(), config.FileID) v.Add(config.name(), config.FileID)
if config.Duration != 0 { if config.Duration != 0 {
v.Add("duration", strconv.Itoa(config.Duration)) v.Add("duration", strconv.Itoa(config.Duration))
@ -469,6 +473,9 @@ func (config VideoConfig) values() (url.Values, error) {
v.Add("parse_mode", config.ParseMode) v.Add("parse_mode", config.ParseMode)
} }
} }
if config.SupportsStreaming {
v.Add("supports_streaming", "true")
}
return v, nil return v, nil
} }

@ -622,7 +622,7 @@ func NewEditMessageCaption(chatID int64, messageID int, caption string) EditMess
ChatID: chatID, ChatID: chatID,
MessageID: messageID, MessageID: messageID,
}, },
Caption: caption, Caption: caption,
} }
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Binary file not shown.