forked from sdslabs/jinora
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slack_utils.coffee
81 lines (71 loc) · 2.35 KB
/
slack_utils.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
slack = require('slack')
listToHash = (list, keyName, innerKey)->
list = list[keyName]
hash = {}
for item in list
if innerKey?
hash[item.id] = item[innerKey]
else
hash[item.id] = item
hash
data = {}
getUsers = (token)->
slack.users.list(token: token)
.then (res) ->
if res.ok
data['users.simple'] = listToHash res, "members", "name"
data['users'] = listToHash res, "members"
getChannels = (token)->
slack.conversations.list (token: token)
.then (res) ->
if res.ok
data['channels.simple'] = listToHash res, "channels", "name"
data['channels'] = listToHash res, "channels"
module.exports = (API_TOKEN, HOOK_URL)->
if API_TOKEN?
getUsers(API_TOKEN)
getChannels(API_TOKEN)
postMessage: (message, channel, nick, icon, attachments)->
messageData =
token: API_TOKEN
text: message
parse: "full"
as_user: false
attachments: attachments
if icon? and (icon[0..7] == 'https://' or icon[0..6] == 'http://')
messageData.icon_url=icon
# If icon is present and is not an emoji
else if icon? and not icon.match /^\:\w*\:$/
messageData.icon_emoji=":#{icon}:"
# If icon is present and is an emoji
else if icon? and icon.match /^\:\w*\:$/
messageData.icon_emoji="#{icon}"
if channel?
messageData.channel = "##{channel}"
if nick?
messageData.username="#{nick}"
slack.chat.postMessage(messageData)
# exporting this to test the method
listToHash: listToHash
parseMessage: (message)->
message
.replace("<!channel>", "@channel")
.replace("<!group>", "@group")
.replace("<!everyone>", "@everyone")
.replace /<#(C\w*)>/g, (match, channelId)->
"##{data['channels.simple'][channelId]}"
.replace /<@(U\w*)>/g, (match, userId)->
"@#{data['users.simple'][userId]}"
.replace /<(\S*)>/g, (match, link)->
link
.replace /http(s)?:\/\/([^\s]*)\|([^\s]*)/g, (match, protocol, href1, href2) ->
return ("http" + (protocol || "") + "://" + href1) if href1 == href2
.replace /&/g, "&"
.replace /</g, "<"
.replace />/g, ">"
userInfoById: (search_id)->
for id, info of data['users']
return info if search_id == id
userInfoByName: (username)->
for id, info of data['users']
return info if info['name'] == username