forked from finnp/gitter-irc-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
76 lines (66 loc) · 2.64 KB
/
index.js
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
var irc = require('irc')
var request = require('request')
var xtend = require('xtend')
var JSONStream = require('JSONStream')
module.exports = function (opts) {
var headers = {
'Accept': 'application/json',
'Authorization': 'Bearer ' + opts.gitterApiKey
}
var ircOpts = xtend({
channels: [opts.ircChannel],
autoConnect: false,
retryCount: 20
}, opts.ircOpts)
var ircClient = new irc.Client(
opts.ircServer || 'irc.freenode.net',
opts.ircNick,
ircOpts
)
ircClient.on('error', function (message) {
console.error('IRC Error:', message)
})
var joinRoomUrl = 'https://api.gitter.im/v1/rooms'
console.log('Connecting to IRC..')
ircClient.connect(function () {
console.log('Connected to IRC, joined', opts.ircChannel)
request.post({url: joinRoomUrl, headers: headers, json: {uri: opts.gitterRoom} }, function (err, req, json) {
if (err) return console.error(err)
var gitterRoomId = json.id
var getGitterMessageUrl = 'https://stream.gitter.im/v1/rooms/' + gitterRoomId + '/chatMessages'
var postGitterMessageUrl = 'https://api.gitter.im/v1/rooms/' + gitterRoomId + '/chatMessages'
request({url: 'https://api.gitter.im/v1/user', headers: headers, json: true}, function (err, res, json) {
if (err) return console.error(err)
var gitterName = json[0].username
console.log('Gitter bot', gitterName, 'on channel', opts.gitterRoom, '(' + gitterRoomId + ')')
var chatStream
function gitterAttach () {
if (chatStream) {
console.log('Reattaching to gitter chat stream...')
chatStream.unpipe()
chatStream.removeAllListeners()
}
chatStream = request({url: getGitterMessageUrl, headers: headers})
chatStream.on('error', gitterAttach)
chatStream.on('end', gitterAttach)
chatStream.pipe(JSONStream.parse())
.on('data', function (message) {
if (message.fromUser.username === gitterName) return
var text = '(' + message.fromUser.username + ') ' + message.text
console.log('gitter:', text)
ircClient.say(opts.ircChannel, text)
})
}
gitterAttach()
ircClient.on('message' + opts.ircChannel, function (from, message) {
if (from === opts.ircNick) return
var text = '`' + from + '` ' + message
console.log('irc:', text)
// TODO: Handle post errors
request.post({url: postGitterMessageUrl, headers: headers, json: {text: text}})
// .pipe(process.stdout) // {"error":"An unknown error occurred"}
})
})
})
})
}