-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
205 lines (183 loc) · 6.14 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
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
require('dotenv').config();
const { SlackAdapter } = require('botbuilder-adapter-slack');
const { Botkit } = require('botkit');
const svc = require('./services');
const meme = require('./memegen');
const util = require('./util');
const fetch = require('node-fetch');
const memeListUrl = `${process.env.BASE_URL}/list`;
const redirectUri = `${process.env.BASE_URL}/install/auth`;
const adapter = new SlackAdapter({
clientSigningSecret: process.env.SLACK_SECRET,
clientId: process.env.CLIENT_ID, // oauth client id
clientSecret: process.env.CLIENT_SECRET, // oauth client secret
scopes: ['commands', 'users:read'], // oauth scopes requested, 'bot' deprecated by Slack in favor of granular permissions
redirectUri, // url to redirect post-login
oauthVersion: 'v2', // or use v2
getTokenForTeam: async (team_id) => {
const team = await svc.getTeam(team_id);
return team.token;
},
getBotUserByTeam: async (team_id) => {
const team = await svc.getTeam(team_id);
return team.userId;
},
});
const controller = new Botkit({
adapter,
});
controller.webserver.set('view engine', 'ejs');
controller.webserver.get('/', async (req, res) => {
const message = req.query['m'];
if (!message) {
res.render('index');
return;
}
const lines = String(message)
.normalize()
.split('|')
.map((it) => it.trim());
let template = lines[0];
let texts = lines
.slice(1)
.map((x) => x && encodeURIComponent(x.split(' ').join('_')));
let url;
const [ids, templates] = await meme.getMemeTemplates();
if (!ids.length) {
res.send('Internal server error');
return;
}
if (templates[template]) {
url = meme.buildUrl(template, texts);
} else if (template.indexOf('http') === 0) {
url = meme.buildUrl('custom', texts, template);
} else {
res.send('Invalid request');
return;
}
res.render('img', { meme: { url, name: template } });
});
controller.webserver.get('/list', async (req, res) => {
const [ids, templates] = await meme.getMemeTemplates();
const memes = ids.map((key) => ({
key,
name: templates[key].name,
url: meme.buildUrl(key, [], null, 250),
}));
res.render('list', { memes });
});
// Create a route for the install link.
// This will redirect the user to Slack's permission request page.
controller.webserver.get('/install', (req, res) => {
res.redirect(adapter.getInstallLink());
});
// Create a route to capture the results of the oauth flow.
// this URL should match the value of the `redirectUri` passed to Botkit.
controller.webserver.get('/install/auth', async (req, res) => {
try {
const results = await controller.adapter.validateOauthCode(
req.query.code
);
// Store token by team in bot state.
let teamId = results.team.id;
let token = results.access_token;
let userId = results.bot_user_id;
await svc.saveTeam({ teamId, token, userId });
// customize your post-install success page
res.send('Success! Bot installed.');
} catch (err) {
console.error('Oauth err:', err);
// customize your post-install failure page
res.status(401);
res.send(err.message);
}
});
controller.on('slash_command', async (bot, message) => {
console.log(message);
if (message.text === '' || message.text === 'help') {
bot.replyPrivate(
message,
`Post a meme: /meme meme-key | top text | bottom text\n👉 Gallery: ${memeListUrl}`
);
} else if (message.text === 'list') {
const [ids, templates] = await meme.getMemeTemplates();
if (!ids.length) {
bot.replyPrivate(
message,
'Failed to list templates, please try again!'
);
return;
}
let helpText = [];
ids.forEach((key) => {
helpText.push(`\`${key}\`: ${templates[key].name}`);
});
helpText.sort();
helpText.push(`👉 Gallery: ${memeListUrl}`);
bot.replyPrivate(message, helpText.join('\n'));
} else {
const lines = message.text.split('|').map((it) => it.trim());
let template = lines[0];
let texts = lines
.slice(1)
.map((x) => x && encodeURIComponent(x.split(' ').join('_')));
let bg;
const [ids, templates] = await meme.getMemeTemplates();
if (!ids.length) {
bot.replyPrivate(
message,
'Failed to get templates, please try again!'
);
return;
}
if (templates[template]) {
bot.replyPublic(message, {
attachments: meme.buildAttachments(
message.user_name,
template,
texts,
bg
),
});
return;
}
if (template.indexOf('http') === 0) {
bot.replyPublic(message, {
attachments: meme.buildAttachments(
message.user_name,
'custom',
texts,
template
),
});
return;
}
if (template.indexOf('@') === 0) {
const name = template.slice(1);
const user = await svc.getUser(bot, message.team_id, name);
if (user) {
bot.replyPublic(message, {
attachments: meme.buildAttachments(
message.user_name,
'custom',
texts,
user.profileImage
),
});
return;
}
}
// Randomize for now
let random = util.randomInt(0, ids.length);
if (lines.length === 1) texts = [template];
template = ids[random];
bot.replyPublic(message, {
attachments: meme.buildAttachments(
message.user_name,
template,
texts
),
});
return;
}
});