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

237 lines
4.9 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';
2017-10-06 21:48:56 +02:00
import User from '../../models/user';
2017-10-06 20:36:46 +02:00
import config from '../../../conf';
2017-10-06 21:30:57 +02:00
import BotCore from '../core';
2017-10-06 22:50:01 +02:00
import _redis from '../../../db/redis';
import prominence = require('prominence');
2017-10-07 12:09:10 +02:00
import getPostSummary from '../../../common/get-post-summary';
2017-10-06 20:36:46 +02:00
2017-10-06 22:50:01 +02:00
const redis = prominence(_redis);
2017-10-06 21:30:57 +02:00
2017-10-07 12:09:10 +02:00
// SEE: https://developers.line.me/media/messaging-api/messages/sticker_list.pdf
const stickers = [
'297',
'298',
'299',
'300',
'301',
'302',
'303',
'304',
'305',
'306',
'307'
];
2017-10-07 11:30:04 +02:00
class LineBot extends BotCore {
private replyToken: string;
private reply(messages: any[]) {
request.post({
url: 'https://api.line.me/v2/bot/message/reply',
headers: {
'Authorization': `Bearer ${config.line_bot.channel_access_token}`
},
json: {
replyToken: this.replyToken,
messages: messages
}
}, (err, res, body) => {
if (err) {
console.error(err);
return;
}
});
}
public async react(ev: any): Promise<void> {
2017-10-07 11:31:55 +02:00
this.replyToken = ev.replyToken;
2017-10-07 20:24:10 +02:00
switch (ev.type) {
// メッセージ
case 'message':
switch (ev.message.type) {
// テキスト
case 'text':
const res = await this.q(ev.message.text);
if (res == null) return;
// 返信
this.reply([{
type: 'text',
text: res
}]);
break;
// スタンプ
case 'sticker':
// スタンプで返信
this.reply([{
type: 'sticker',
packageId: '4',
stickerId: stickers[Math.floor(Math.random() * stickers.length)]
}]);
break;
}
break;
// postback
case 'postback':
const data = ev.postback.data;
const cmd = data.split('|')[0];
const arg = data.split('|')[1];
switch (cmd) {
case 'showtl':
this.showUserTimelinePostback(arg);
break;
}
break;
2017-10-07 12:09:10 +02:00
}
2017-10-07 11:30:04 +02:00
}
public static import(data) {
const bot = new LineBot();
bot._import(data);
return bot;
}
public async showUserCommand(q: string) {
2017-10-07 12:15:32 +02:00
const user = await require('../../endpoints/users/show')({
2017-10-07 11:30:04 +02:00
username: q.substr(1)
}, this.user);
2017-10-07 20:24:10 +02:00
const actions = [];
actions.push({
type: 'postback',
label: 'タイムラインを見る',
data: `showtl|${user.id}`
});
if (user.account.twitter) {
2017-10-07 20:24:10 +02:00
actions.push({
type: 'uri',
label: 'Twitterアカウントを見る',
uri: `https://twitter.com/${user.account.twitter.screen_name}`
2017-10-07 20:24:10 +02:00
});
}
actions.push({
type: 'uri',
label: 'Webで見る',
2018-03-27 05:53:56 +02:00
uri: `${config.url}/@${user.username}`
2017-10-07 20:24:10 +02:00
});
2017-10-07 11:30:04 +02:00
this.reply([{
type: 'template',
altText: await super.showUserCommand(q),
template: {
type: 'buttons',
thumbnailImageUrl: `${user.avatar_url}?thumbnail&size=1024`,
title: `${user.name} (@${user.username})`,
text: user.description || '(no description)',
2017-10-07 20:24:10 +02:00
actions: actions
2017-10-07 11:30:04 +02:00
}
}]);
2017-11-11 20:48:16 +01:00
return null;
2017-10-07 11:30:04 +02:00
}
2017-10-07 12:09:10 +02:00
public async showUserTimelinePostback(userId: string) {
const tl = await require('../../endpoints/users/posts')({
user_id: userId,
limit: 5
}, this.user);
2017-10-07 20:24:10 +02:00
const text = `${tl[0].user.name}さんのタイムラインはこちらです:\n\n` + tl
2017-10-07 12:09:10 +02:00
.map(post => getPostSummary(post))
.join('\n-----\n');
this.reply([{
type: 'text',
text: text
}]);
}
2017-10-07 11:30:04 +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-07 12:29:32 +02:00
handler.on('event', async (ev) => {
2017-10-06 21:30:57 +02:00
const sourceId = ev.source.userId;
2017-10-06 22:50:01 +02:00
const sessionId = `line-bot-sessions:${sourceId}`;
2017-10-06 21:30:57 +02:00
2017-10-07 20:24:10 +02:00
const session = await redis.get(sessionId);
2017-10-07 11:30:04 +02:00
let bot: LineBot;
2017-10-06 22:50:01 +02:00
2017-10-07 20:24:10 +02:00
if (session == null) {
2017-10-06 21:48:56 +02:00
const user = await User.findOne({
'account.line': {
2017-10-06 21:48:56 +02:00
user_id: sourceId
}
});
2017-10-07 11:30:04 +02:00
bot = new LineBot(user);
2017-10-06 23:43:36 +02:00
2017-10-07 11:30:04 +02:00
bot.on('signin', user => {
2017-10-06 23:03:16 +02:00
User.update(user._id, {
$set: {
'account.line': {
2017-10-06 23:03:16 +02:00
user_id: sourceId
2017-10-06 21:48:56 +02:00
}
2017-10-06 23:03:16 +02:00
}
2017-10-06 21:48:56 +02:00
});
2017-10-06 23:03:16 +02:00
});
2017-10-06 21:48:56 +02:00
2017-10-07 11:30:04 +02:00
bot.on('signout', user => {
2017-10-06 23:43:36 +02:00
User.update(user._id, {
$set: {
'account.line': {
2017-10-06 23:43:36 +02:00
user_id: null
}
}
});
});
2017-10-07 11:30:04 +02:00
redis.set(sessionId, JSON.stringify(bot.export()));
2017-10-06 22:50:01 +02:00
} else {
2017-10-07 20:24:10 +02:00
bot = LineBot.import(JSON.parse(session));
2017-10-06 21:30:57 +02:00
}
2017-10-07 11:30:04 +02:00
bot.on('updated', () => {
redis.set(sessionId, JSON.stringify(bot.export()));
2017-10-06 22:50:01 +02:00
});
2017-10-07 20:24:10 +02:00
if (session != null) bot.refreshUser();
2017-10-07 11:30:04 +02:00
bot.react(ev);
2017-10-06 21:30:57 +02:00
});
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 => {
2017-10-07 12:29:32 +02:00
handler.emit('event', ev);
2017-10-06 21:30:57 +02:00
});
2017-10-06 20:36:46 +02:00
res.sendStatus(200);
} else {
res.sendStatus(400);
}
});
};