-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.ts
212 lines (185 loc) · 4.84 KB
/
index.ts
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
// XXX: sharpをcanvasより先に読み込むとエラーになるため、ここで読み込んでおく
// https://github.com/Automattic/node-canvas/issues/930
import 'canvas';
import dotenv from 'dotenv';
dotenv.config();
import Fastify from 'fastify';
import os from 'os';
import { eventClient, messageClient, tsgEventClient, webClient } from './lib/slack';
import yargs from 'yargs';
import logger from './lib/logger';
import fastifyExpress from '@fastify/express';
import fastifyFormbody from '@fastify/formbody';
import sharp from 'sharp';
import { throttle, uniq } from 'lodash';
const log = logger.child({bot: 'index'});
process.on('unhandledRejection', (error: Error, promise: Promise<any>) => {
log.error(`unhandledRejection at: ${promise} reason: ${error.message}`, {error, stack: error.stack, promise});
});
// Disable the cache since it likely hits the swap anyway
sharp.cache(false);
const fastify = Fastify({
logger: logger.child({bot: 'http/index'}),
pluginTimeout: 50000,
});
const allBots = [
'summary',
'mahjong',
'pocky',
'emoji-notifier',
'sushi-bot',
'shogi',
'tiobot',
'checkin',
'tahoiya',
'channel-notifier',
'prime',
'dajare',
'sunrise',
'ahokusa',
// ...(word2vecInstalled ? ['vocabwar'] : []),
'ricochet-robots',
'scrapbox',
'slack-log',
'welcome',
'deploy',
'achievements',
'mail-hook',
'wordhero',
'wordhero/crossword',
'oauth',
'tunnel',
'voiperrobot',
'atcoder',
'lyrics',
'better-custom-response',
'emoxpand',
'ponpe',
'anime',
'anime/anison',
'oogiri',
'sorting-riddles',
'tsglive',
'emoji-modifier',
'context-free',
'room-gacha',
'taiko',
'hayaoshi',
'twitter-dm-notifier',
'hitandblow',
'discord',
'octas',
'pwnyaa',
'amongyou',
'api',
'hangman',
'hakatashi-visor',
'nojoin',
'remember-english',
'golfbot',
'kirafan/quiz',
'topic',
'bungo-quiz',
'adventar',
'jantama',
'tabi-gatcha',
'achievement-quiz',
'wadokaichin',
'wordle-battle',
'slow-quiz',
'dicebot',
'taimai',
'map-guessr',
'character-quiz',
'shmug',
'pilot',
'qrcode-quiz',
'oneiromancy',
'auto-archiver',
];
log.info('slackbot started');
const argv = yargs
.array('only')
.choices('only', allBots)
.default('only', allBots)
.default('startup', 'シュッシュッ (起動音)')
.argv;
const plugins = uniq(argv.only);
if (plugins.length !== argv.only.length) {
log.info(`Some plugins are specified more than once. Duplicated plugins were removed.`)
}
eventClient.on('error', (error) => {
log.error(`EventsAPI error ${error.message}`, {error, stack: error.stack});
});
(async () => {
await fastify.register(fastifyFormbody);
await fastify.register(fastifyExpress);
fastify.use('/slack-event', (req, res, next) => {
if (!{}.hasOwnProperty.call(req.headers, 'x-slack-signature')) {
res.statusCode = 400;
res.end('Bad Request');
return;
}
next();
});
fastify.use('/slack-event', eventClient.expressMiddleware());
fastify.use('/slack-message', messageClient.requestListener());
const loadedPlugins = new Set<string>();
const initializationMessage = await webClient.chat.postMessage({
username: `tsgbot [${os.hostname()}]`,
channel: process.env.CHANNEL_SANDBOX,
text: `起動中⋯⋯ (${loadedPlugins.size}/${plugins.length})`,
attachments: plugins.map((name) => ({
color: '#F44336',
text: `*loading:* ${name}`,
})),
});
const throttleLoadingMessageUpdate = throttle(() => {
webClient.chat.update({
channel: process.env.CHANNEL_SANDBOX,
ts: initializationMessage.ts as string,
text: `起動中⋯⋯ (${loadedPlugins.size}/${plugins.length})`,
attachments: [
{
color: '#4CAF50',
text: `*loaded:* ${Array.from(loadedPlugins).join(', ')}`,
},
...plugins.filter((name) => !loadedPlugins.has(name)).map((name) => ({
color: '#F44336',
text: `*loading:* ${name}`,
})),
],
})
}, 0.5 * 1000);
await Promise.all(plugins.map(async (name) => {
const plugin = await import(`./${name}`);
if (typeof plugin === 'function') {
await plugin({webClient, eventClient: tsgEventClient, messageClient});
}
if (typeof plugin.default === 'function') {
await plugin.default({webClient, eventClient: tsgEventClient, messageClient});
}
if (typeof plugin.server === 'function') {
await fastify.register(plugin.server({webClient, eventClient: tsgEventClient, messageClient}));
}
loadedPlugins.add(name);
log.info(`plugin "${name}" successfully loaded`);
throttleLoadingMessageUpdate();
}));
fastify.listen({
port: process.env.PORT ? parseInt(process.env.PORT) : 21864,
host: '0.0.0.0',
}, (error, address) => {
if (error) {
log.error(`fastify.listen error ${error.message}`, {error, stack: error.stack});
} else {
log.info(`Server launched at ${address}`);
}
});
log.info('Launched');
webClient.chat.postMessage({
username: `tsgbot [${os.hostname()}]`,
channel: process.env.CHANNEL_SANDBOX,
text: argv.startup,
});
})();