forked from carlosdp/twiliogo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessage.go
executable file
·92 lines (71 loc) · 2.57 KB
/
message.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package twiliogo
import (
"encoding/json"
"net/url"
)
type Message struct {
Sid string `json:"sid"`
DateCreated string `json:"date_created"`
DateUpdated string `json:"date_updated"`
DateSent string `json:"date_sent"`
AccountSid string `json:"account_sid"`
From string `json:"from"`
MessagingServiceSid string `json:"messaging_service_sid"`
To string `json:"to"`
Body string `json:"body"`
NumSegments string `json:"num_segments"`
Status string `json:"status"`
Direction string `json:"direction"`
Price string `json:"price"`
PriceUnit string `json:"price_unit"`
ApiVersion string `json:"api_version"`
Uri string `json:"uri"`
}
func NewMessage(client Client, from string, to string, content ...Optional) (*Message, error) {
return sendMessage(client, from, "", to, content...)
}
func NewMessageFromService(client Client, fromServiceSid string, to string, content ...Optional) (*Message, error) {
return sendMessage(client, "", fromServiceSid, to, content...)
}
func sendMessage(client Client, fromNumber, fromMessagingServiceSid, to string, content ...Optional) (*Message, error) {
var message *Message
params := url.Values{}
if fromNumber != "" {
params.Set("From", fromNumber)
} else if fromMessagingServiceSid != "" {
params.Set("MessagingServiceSid", fromMessagingServiceSid)
} else {
return nil, Error{"Either From phone number or MessageServiceSid must be provided."}
}
params.Set("To", to)
for _, optional := range content {
param, value := optional.GetParam()
if param != "Body" && param != "MediaUrl" && param != "StatusCallback" && param != "ApplicationSid" && param != "MessagingServiceSid" {
return nil, Error{"Only allowed params are Body, MediaUrl, StatusCallback, ApplicationSid, MessagingServiceSid"}
}
if param == "Body" && len(value) > 1560 {
value = value[:1560]
}
params.Set(param, value)
}
if params.Get("Body") == "" && params.Get("MediaUrl") == "" {
return nil, Error{"Must have at least a Body or MediaUrl"}
}
res, err := client.post(params, "/Messages.json")
if err != nil {
return message, err
}
message = new(Message)
err = json.Unmarshal(res, message)
return message, err
}
func GetMessage(client Client, sid string) (*Message, error) {
var message *Message
res, err := client.get(url.Values{}, "/Messages/"+sid+".json")
if err != nil {
return nil, err
}
message = new(Message)
err = json.Unmarshal(res, message)
return message, err
}