Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SendFile: Bare minimum to work #13

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package mbotapi
import "github.com/satori/go.uuid"

// Creates a User from ID(int64)
func NewUserFromID(id int64) User {
func NewUserFromID(id string) User {
return User{
ID: id,
}
Expand Down Expand Up @@ -164,12 +164,13 @@ func NewButtonTemplate(text string) ButtonTemplate {

// Creates an empty Receipt Template
func NewReceiptTemplate(rname string) ReceiptTemplate {
uuid4 := uuid.NewV4()
return ReceiptTemplate{
TemplateBase: TemplateBase{
Type: "receipt",
},
RecipientName: rname,
ID: uuid.NewV4().String(),
ID: uuid4.String(),
Currency: "USD",
PaymentMethod: "",
Items: []OrderItem{},
Expand Down
58 changes: 52 additions & 6 deletions messenger.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import (
"net/http"
"os"
"path/filepath"
"net/textproto"
"mime"
)

// This defines a bot
Expand Down Expand Up @@ -42,7 +44,7 @@ func NewBotAPI(token string, vtoken string, secret string) *BotAPI {
// It takes Request struct encoded into a buffer of json bytes
// The APIResponse contains the error from FB if any
// Should NOT be directly used, Use Send / SendFile
func (bot *BotAPI) MakeRequest(b *bytes.Buffer) (APIResponse, error) {
func (bot *BotAPI) MakeRequest(b *bytes.Buffer) (APIResponse, error) {
uri := fmt.Sprintf(APIEndpoint, bot.Token)

req, _ := http.NewRequest("POST", uri, b)
Expand All @@ -66,6 +68,31 @@ func (bot *BotAPI) MakeRequest(b *bytes.Buffer) (APIResponse, error) {
return rsp, nil
}

func (bot *BotAPI) MakeRequestMultipart(contentType string, body io.Reader) (APIResponse, error) {
//uri := "http://localhost:1234/asdf"
uri := fmt.Sprintf(APIEndpoint, bot.Token)

req, _ := http.NewRequest("POST", uri, body)
req.Header.Set("Content-Type", contentType)
resp, err := bot.Client.Do(req)
if err != nil {
return APIResponse{}, err
}
defer resp.Body.Close()

var rsp APIResponse
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&rsp)
if err != nil {
return APIResponse{}, nil
}

if resp.StatusCode != 200 {
return rsp, errors.New(http.StatusText(resp.StatusCode))
}
return rsp, nil
}

// This function helps send messages to users
// It takes Message / GenericTemplate / ButtonTemplate / ReceiptTemplate and
// sends it to the user
Expand Down Expand Up @@ -93,6 +120,7 @@ func (bot *BotAPI) Send(u User, c interface{}, notif string) (APIResponse, error
Recipient: u,
Message: c.(Message),
NotifType: n,
MessagingType: "RESPONSE",
}

case GenericTemplate:
Expand Down Expand Up @@ -166,26 +194,44 @@ func (bot *BotAPI) SendFile(u User, path string) (APIResponse, error) {
}
defer file.Close()

ftypes, err := mime.ExtensionsByType(path)
if err != nil {
return APIResponse{}, err
}
if len(ftypes) == 0 {
return APIResponse{}, err
}

return bot.SendStream(u, filepath.Base(path), ftypes[0], file)
}

func (bot *BotAPI) SendStream(u User, filename, contentType string, r io.Reader) (APIResponse, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("filedata", filepath.Base(path))
//part, err := writer.CreateFormFile("filedata", filepath.Base(path))
hdr := textproto.MIMEHeader{
"Content-Disposition": []string{"name=\"filedata\"; filename=\""+filename+"\"", },
"Content-Type": []string{ contentType, },
}
part, err := writer.CreatePart(hdr)
if err != nil {
return APIResponse{}, err
}
_, err = io.Copy(part, file)
_, err = io.Copy (part, r)

usr, _ := json.Marshal(u)
_ = writer.WriteField("recipient", string(usr))
img := NewImageFromURL("")
im, _ := json.Marshal(img)
_ = writer.WriteField("message", string(im))

err = writer.Close()
if err != nil {
contentType2 := writer.FormDataContentType()

if err := writer.Close(); err != nil {
return APIResponse{}, err
}

return bot.MakeRequest(body)
return bot.MakeRequestMultipart(contentType2, body)
}

//This function verifies the message
Expand Down
6 changes: 3 additions & 3 deletions receive.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ type Response struct {

// This defines an Entry in the payload by webhook
type Entry struct {
PageID int64 `json:"id"`
PageID string `json:"id"`
Time int64 `json:"time"`
Messaging []Callback `json:"messaging"`
}
Expand Down Expand Up @@ -53,12 +53,12 @@ func (c Callback) IsDelivery() bool {
// This defines an user
// One of the fields will be set to identify the user
type User struct {
ID int64 `json:"id,omitempty,string"`
ID string `json:"id,omitempty"`
PhoneNumber string `json:"phone_number,omitempty"`
}

type Page struct {
ID int64 `json:"id,string"`
ID string `json:"id"`
}

// Ref contains the `data-ref` set for message optin for the bot
Expand Down
3 changes: 2 additions & 1 deletion send.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type Request struct {
Message Message `json:"message,omitempty"`
Action Action `json:"sender_action,omitempty"`
NotifType string `json:"notification_type"`
MessagingType string `json:"messaging_type,omitempty"`
}

type Action string
Expand Down Expand Up @@ -56,7 +57,7 @@ type AttachmentPayload interface{}

// Used as payload for type image/audio/video/file
type FilePayload struct {
URL string `json:"url"`
URL string `json:"url,omitempty"`
}

type TemplateBase struct {
Expand Down