iceshrimp-legacy/src/api/bot/interfaces/line.ts

81 lines
1.8 KiB
TypeScript
Raw Normal View History

2017-10-06 20:36:46 +02:00
import * as EventEmitter from 'events';
import * as express from 'express';
2017-10-06 21:30:57 +02:00
import * as request from 'request';
2017-10-06 20:36:46 +02:00
import * as crypto from 'crypto';
//import User from '../../models/user';
import config from '../../../conf';
2017-10-06 21:30:57 +02:00
import BotCore from '../core';
2017-10-06 20:36:46 +02:00
2017-10-06 21:30:57 +02:00
const sessions: Array<{
sourceId: string;
2017-10-06 20:36:46 +02:00
session: BotCore;
2017-10-06 21:30:57 +02:00
}> = [];
2017-10-06 20:36:46 +02:00
module.exports = async (app: express.Application) => {
if (config.line_bot == null) return;
const handler = new EventEmitter();
2017-10-06 21:30:57 +02:00
handler.on('message', async (ev) => {
// テキスト以外(スタンプなど)は無視
if (ev.message.type !== 'text') return;
const sourceId = ev.source.userId;
let session = sessions.find(s => {
return s.sourceId === sourceId;
});
if (!session) {
session = {
sourceId: sourceId,
session: new BotCore()
};
sessions.push(session);
}
const res = await session.session.q(ev.message.text);
request({
url: 'https://api.line.me/v2/bot/message/reply',
headers: {
'Authorization': `Bearer ${config.line_bot.channel_access_token}`
},
json: {
replyToken: ev.replyToken,
messages: [{
type: 'text',
text: res
}]
}
}, (err, res, body) => {
if (err) {
console.error(err);
return;
}
});
});
2017-10-06 20:36:46 +02:00
app.post('/hooks/line', (req, res, next) => {
2017-10-06 21:30:57 +02:00
// req.headers['x-line-signature'] は常に string ですが、型定義の都合上
2017-10-06 20:36:46 +02:00
// string | string[] になっているので string を明示しています
2017-10-06 21:30:57 +02:00
const sig1 = req.headers['x-line-signature'] as string;
2017-10-06 20:36:46 +02:00
2017-10-06 21:30:57 +02:00
const hash = crypto.createHmac('SHA256', config.line_bot.channel_secret)
.update((req as any).rawBody);
2017-10-06 20:36:46 +02:00
const sig2 = hash.digest('base64');
// シグネチャ比較
if (sig1 === sig2) {
2017-10-06 21:30:57 +02:00
req.body.events.forEach(ev => {
handler.emit(ev.type, ev);
});
2017-10-06 20:36:46 +02:00
res.sendStatus(200);
} else {
res.sendStatus(400);
}
});
};