This repository was archived by the owner on Aug 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnewuser.js
217 lines (198 loc) · 6.62 KB
/
newuser.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
const https = require('https');
const RTM_EVENTS = require('@slack/client').RTM_EVENTS;
const winston = require('winston');
const storage = require('node-persist');
const META = {
name: 'newuser',
short: 'Greets new users and sends them a copy of the code of conduct',
examples: [
'when a user joins #general they will be greeted privately',
],
};
// TODO :: Move this URL to the configuration file
const cocURL = 'https://raw.githubusercontent.com/mena-devs/code-of-conduct/master/GREETING.md';
/**
* Takes the UserList (Semi-Column sepearated String)
* prepends a newUser to the list and maintains a maximum number of items
* returns the new string for storage
*
* @param {[type]} userList [description]
* @param {[type]} maxItems [description]
* @param {[type]} newUser [description]
*
* @return {[type]} [description]
*/
function prependUser(userList, maxItems, newUser) {
// Append to list only if newUser is not found
if (userList.indexOf(newUser) !== -1) {
return userList;
}
let splitMembers = userList.split(';');
// -1 cause Arrays in JS start from the 0 index
if (splitMembers.length < maxItems - 1) {
splitMembers = splitMembers.slice(0, maxItems - 1);
}
splitMembers.unshift(newUser);
return splitMembers.join(';');
}
/**
* Takes a ';' separated value list and counts the number of entries in it
*
* @param {[type]} userList [description]
*
* @return {[type]} [description]
*/
function countMembers(userList) {
return userList.split(';').length;
}
/**
* Retrieve the list of all the users in storage
* if empty, populate it with the first entry
* if not, append to the list the new entry
* up to a maximum of 10 entries
*
* @param {[type]} config [description]
* @param {[type]} newUserID [description]
*
* @return {[type]} [description]
*/
function storeNewMember(config, newUserID) {
// Get the total number of users to store from the configuration
const maxRecentUsers = config.plugins.newuser.max_recent_users;
storage.init({ dir: config.plugins.system.recent_members_path })
.then(() => storage.getItem('recent_users'))
.then((users) => {
if (!users) {
storage.setItem('recent_users', newUserID)
.then(() => winston.info(`Added ${newUserID} to storage!`));
} else {
// Append new user ID
const userList = prependUser(users, maxRecentUsers, newUserID);
storage.setItem('recent_users', userList)
.then(() => winston.info('Recent members list updated!'));
}
});
}
/**
* Retrieves user information from ID
* TODO: Move it to utils.js
*
* @param {[type]} bot [description]
* @param {[type]} id [description]
*
* @return {String} Username associated the ID provided
*/
function findUser(web, id) {
return new Promise((resolve, reject) => {
// Send a private message to the user with the CoC
web.users.info(id, (err, res) => {
if (err) {
reject(`I don't know of a ${id}`);
} else {
resolve(res.user.name);
}
});
});
}
/**
* Retrieve the CoC from the github URL
*
* @return {[type]} [description]
*/
function retrieveCoC() {
return new Promise((resolve, reject) => {
https.get(cocURL, (res) => {
// Combine the chunks that are retrieved
const responseParts = [];
res.setEncoding('utf8');
res.on('data', (d) => {
responseParts.push(d);
});
// Combine the chunks and resolve
res.on('end', () => {
resolve(responseParts.join(''));
});
}).on('error', (e) => {
reject(`Could not retrieve CoC ${e}`);
});
});
}
/**
* Send a private message to a user
*
* @param {[type]} web [description]
* @param {[type]} receiver [description]
* @param {[type]} message [description]
*
* @return {[type]} [description]
*/
function privateMessage(web, receiver, message) {
return new Promise((resolve, reject) => {
// Send a private message to the user with the CoC
const msg = `Hi <@${receiver}>! \n\
I'm *Bostantine Androidaou* MENA Dev's butler. I'm at your service, all you \
gotta do is to call \`@bosta help\`. In the meantime, here's a message \
from the admins: \n\n ${message}`;
web.chat.postMessage(receiver, msg, { as_user: true }, (err) => {
if (err) {
reject(`Welcome message could not be sent: ${err}`);
} else {
resolve(receiver);
}
});
});
}
/**
* Main
*
* @param {[type]} bot [description]
* @param {[type]} rtm [description]
* @param {[type]} web [description]
* @param {[type]} config [description]
*
* @return {[type]} [description]
*/
function register(bot, rtm, web, config) {
rtm.on(RTM_EVENTS.MESSAGE, (message) => {
if (message.subtype === 'channel_join'
&& message.channel === config.main.general_chan_id) {
web.reactions.add('wave',
{ channel: message.channel, timestamp: message.ts })
.catch((error) => {
winston.error(`${META.name} - Channel Join - Error: ${error}`);
});
retrieveCoC()
.then(data => privateMessage(web, message.user, data))
.then((user) => {
storeNewMember(config, user);
winston.info(`Sent greeting to: <@${user}>`);
})
.catch((error) => {
winston.error(`${META.name} - Retrieve CoC - Error: ${error}`);
});
}
// Manual greet
if (message.text) {
const pattern = /<@([^>]+)>:? greet <@([^>]+)>:?/;
const [, target, userId] = message.text.match(pattern) || [];
const user = { id: userId, name: '' };
if (target === bot.self.id) {
findUser(web, user.id)
.then((response) => { user.name = response; })
.then(() => retrieveCoC())
.then(data => privateMessage(web, user.id, data))
.then((userRId) => {
storeNewMember(config, userRId);
winston.info(`Sent greeting to: <@${userRId}>`);
})
.catch((error) => {
winston.error(`${META.name} - Manual Greet - Error: ${error}`);
});
}
}
});
}
module.exports = {
register,
META,
};