forked from hubotio/hubot
/
twilio.coffee
94 lines (69 loc) · 2.16 KB
/
twilio.coffee
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
93
94
Robot = require 'robot'
Http = require 'http'
Https = require 'https'
Qs = require 'querystring'
class Twilio extends Robot
constructor: ->
@config =
sid: process.env.HUBOT_SMS_SID
token: process.env.HUBOT_SMS_TOKEN
from: process.env.HUBOT_SMS_FROM
super
send: (user, strings...) ->
message = strings.join "\n"
@post message, user.id, (error, body) ->
if error or not body
console.log "error sending response: #{error}"
else
console.log "successful sending #{body}"
reply: (user, strings...) ->
strings.forEach (str) =>
@send user, "#{user.name}: #{str}"
respond: (regex, callback) ->
@hear regex, callback
run: ->
console.log "Hubot: the SMS reader."
server = Http.createServer (request, response) =>
payload = Qs.parse(request.url)
@handle payload.Body, payload.From if payload.Body and payload.From
response.writeHead 200, 'Content-Type': 'text/plain'
response.end()
server.listen (parseInt(process.env.PORT) || 8080), "0.0.0.0"
handle: (body, from) ->
return if body.length == 0
user = @userForId from
@receive new Robot.TextMessage user, body
post: (message, to, callback) ->
host = "api.twilio.com"
path = "/2010-04-01/Accounts/#{@config.sid}/SMS/Messages.json"
auth = new Buffer(@config.sid + ':' + @config.token).toString("base64")
headers =
'Authorization': "Basic " + auth
'Content-Type': "application/x-www-form-urlencoded"
'Host': host
params = Qs.stringify
'From': @config.from
'To': to
'Body': message
headers['Content-Length'] = params.length
opts =
host: host
port: 443
method: "POST"
path: path
headers: headers
console.log opts
request = Https.request opts, (response) ->
data = ""
response.setEncoding "utf8"
response.on "data", (chunk) ->
data += chunk
response.on "end", ->
body = JSON.parse data
if response.statusCode is 201
callback null, body
else
callback body.message
request.write params
request.end()
exports.Twilio = Twilio