-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
62 lines (43 loc) · 1.43 KB
/
server.js
File metadata and controls
62 lines (43 loc) · 1.43 KB
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
const Koa = require('koa');
const pug = require('pug');
const path = require('path');
const Router = require('koa-router');
const mongoose = require('mongoose')
const sendMessage = require('./sendMessage');
const search = require('./wikipedia');
const config = require('./config');
const logger = require('./logger');
const History = require('./History');
const app = new Koa();
const router = new Router();
app.use(require('koa-bodyparser')());
router.post(`/${config.bot_token}`, async (ctx, next) => {
try {
const {message: {text, chat: {id: chatId}, from: {id: userId}}} = ctx.request.body;
if(text === '/history') {
const entities = await History.find({ user: userId })
.sort({ createdAt: -1})
.limit(10)
const history = entities.map(entity => `${entity.text}`)
await sendMessage (chatId, history.join('\n'));
ctx.body = 'ok';
return;
}
await History.create({
user: userId,
text,
createdAt: Date.now()
});
const results = await search (text);
const msg = pug.renderFile (path.join (__dirname, 'message.pug'), {
results,
})
await sendMessage (chatId, msg, 'HTML');
} catch (err) {
logger.error(err)
}
ctx.body = 'ok';
})
app.use(router.routes());
mongoose.connect(config.mongodb_uri);
app.listen(config.port);