ai/src/modules/keyword/index.ts

72 lines
1.8 KiB
TypeScript
Raw Normal View History

2018-08-13 08:54:56 +00:00
import from '../../ai';
import IModule from '../../module';
import config from '../../config';
import MessageLike from '../../message-like';
import serifs from '../../serifs';
2018-08-13 09:17:38 +00:00
const MeCab = require('mecab-async');
2018-08-13 08:54:56 +00:00
2018-08-13 09:26:45 +00:00
function kanaToHira(str: string) {
return str.replace(/[\u30a1-\u30f6]/g, match => {
const chr = match.charCodeAt(0) - 0x60;
return String.fromCharCode(chr);
});
}
2018-08-13 08:54:56 +00:00
export default class KeywordModule implements IModule {
public name = 'keyword';
private ai: ;
2018-08-13 09:17:38 +00:00
private tokenizer: any;
2018-08-13 08:54:56 +00:00
public install = (ai: ) => {
this.ai = ai;
2018-08-13 09:17:38 +00:00
this.tokenizer = new MeCab();
this.tokenizer.command = config.mecab;
setTimeout(this.say, 1000 * 60 * 60);
2018-08-13 08:54:56 +00:00
}
2018-08-13 09:17:38 +00:00
private say = async (msg?: MessageLike) => {
2018-08-13 08:54:56 +00:00
const tl = await this.ai.api('notes/local-timeline');
const interestedNotes = tl.filter(note => note.userId !== this.ai.account.id && note.text != null);
2018-08-13 09:17:38 +00:00
let keywords: string[][] = [];
2018-08-13 08:54:56 +00:00
2018-08-13 09:17:38 +00:00
await Promise.all(interestedNotes.map(note => new Promise((res, rej) => {
this.tokenizer.parse(note.text, (err, tokens) => {
2018-08-13 09:20:39 +00:00
const keywordsInThisNote = tokens.filter(token => token[2] == '固有名詞' && token[8] != null);
2018-08-13 09:17:38 +00:00
keywords = keywords.concat(keywordsInThisNote);
res();
});
})));
2018-08-13 08:54:56 +00:00
console.log(keywords);
const keyword = keywords[Math.floor(Math.random() * keywords.length)];
2018-08-13 09:17:38 +00:00
const text = serifs.KEYWORD
.replace('{word}', keyword[0])
2018-08-13 09:26:45 +00:00
.replace('{reading}', kanaToHira(keyword[8]))
2018-08-13 09:17:38 +00:00
if (msg) {
msg.reply(text);
} else {
this.ai.post(text);
}
2018-08-13 08:54:56 +00:00
}
public onMention = (msg: MessageLike) => {
2018-08-13 09:26:45 +00:00
if (msg.user.isAdmin && msg.isMessage && msg.text && msg.text.includes('なんか皆に言って')) {
this.say(msg);
return true;
} else if (msg.text && msg.text.includes('なんか言って')) {
2018-08-13 09:17:38 +00:00
this.say(msg);
2018-08-13 08:54:56 +00:00
return true;
} else {
return false;
}
}
}