Initial import.
This commit is contained in:
83
conn/twilio/config.go
Normal file
83
conn/twilio/config.go
Normal file
@@ -0,0 +1,83 @@
|
||||
package twilio
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Contacts []string `yaml:"contacts"`
|
||||
contacts map[string]bool
|
||||
AccountSID string `yaml:"account_sid"`
|
||||
AuthToken string `yaml:"auth_token"`
|
||||
Number string `yaml:"telno"` // kas' telno
|
||||
}
|
||||
|
||||
func (cfg *Config) postURL() string {
|
||||
return fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json",
|
||||
cfg.AccountSID)
|
||||
}
|
||||
|
||||
func (cfg *Config) buildContacts() {
|
||||
cfg.contacts = map[string]bool{}
|
||||
for _, telno := range cfg.Contacts {
|
||||
cfg.contacts[telno] = true
|
||||
}
|
||||
}
|
||||
|
||||
func (cfg *Config) NumberAuthorized(s string) bool {
|
||||
if cfg.contacts == nil || len(cfg.contacts) != len(cfg.Contacts) {
|
||||
cfg.buildContacts()
|
||||
}
|
||||
|
||||
return cfg.contacts[s]
|
||||
}
|
||||
|
||||
func validate(cfg *Config) error {
|
||||
if len(cfg.Contacts) == 0 {
|
||||
return errors.New("twilio: no authorized numbers (you won't be able to receive any messages)")
|
||||
}
|
||||
|
||||
if cfg.AccountSID == "" {
|
||||
return errors.New("twilio: missing account SID")
|
||||
}
|
||||
|
||||
if cfg.AuthToken == "" {
|
||||
return errors.New("twilio: missing auth token")
|
||||
}
|
||||
|
||||
if cfg.Number == "" {
|
||||
return errors.New("twilio: no number configured")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var config *Config
|
||||
|
||||
func SetConfig(cfg *Config) error {
|
||||
if err := validate(cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
config = cfg
|
||||
return nil
|
||||
}
|
||||
|
||||
func Send(to string, message string) error {
|
||||
form := url.Values{
|
||||
"Body": {message},
|
||||
"From": {config.Number},
|
||||
"To": {to},
|
||||
}
|
||||
|
||||
resp, err := http.PostForm(config.postURL(), form)
|
||||
if err != nil {
|
||||
log.Printf("twilio send: %s", err)
|
||||
}
|
||||
|
||||
resp.Body.Close()
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user