123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242 |
- "use strict";
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Message = void 0;
- const koishi_1 = require("koishi");
- require("koishi-adapter-onebot");
- const command_1 = require("./command");
- const loggers_1 = require("./loggers");
- const utils_1 = require("./utils");
- const logger = (0, loggers_1.getLogger)('qqbot');
- const cqUrlFix = (factory) => (...args) => factory(...args).replace(/(?<=\[CQ:.*)url=(?=(base64|file|https?):\/\/)/, 'file=');
- exports.Message = {
- Image: cqUrlFix(koishi_1.segment.image),
- Video: cqUrlFix(koishi_1.segment.video),
- Voice: cqUrlFix(koishi_1.segment.audio),
- ellipseBase64: (msg) => msg.replace(/(?<=\[CQ:.*base64:\/\/).*?(,|\])/g, '...$1'),
- separateAttachment: (msg) => {
- const attachments = [];
- const message = msg.replace(/\[CQ:(video|record),.*?\]/g, code => {
- attachments.push(code);
- return '';
- });
- return { message, attachments };
- },
- };
- class default_1 {
- constructor(opt) {
- this.messageQueues = {};
- this.tempSenders = {};
- this.next = (type, id) => {
- const queue = this.messageQueues[`${type}:${id}`];
- if (queue && queue.length) {
- queue[0]().then(() => {
- queue.shift();
- if (!queue.length)
- delete this.messageQueues[`${type}:${id}`];
- else
- this.next(type, id);
- });
- }
- };
- this.enqueue = (type, id, resolver) => {
- var _a, _b;
- let wasEmpty = false;
- const queue = (_a = this.messageQueues)[_b = `${type}:${id}`] || (_a[_b] = (() => { wasEmpty = true; return []; })());
- queue.push(() => (0, koishi_1.sleep)(200).then(resolver));
- logger.debug(`no. of message currently queued for ${type}:${id}: ${queue.length}`);
- if (wasEmpty)
- this.next(type, id);
- };
- this.getChat = (session) => __awaiter(this, void 0, void 0, function* () {
- switch (session.subtype) {
- case 'private':
- if (session.sender.groupId) {
- const friendList = yield session.bot.getFriendList();
- if (!friendList.some(friendItem => friendItem.userId === session.userId)) {
- this.tempSenders[session.userId] = session.sender.groupId;
- return {
- chatID: {
- qq: Number(session.userId),
- group: Number(session.sender.groupId),
- toString: () => session.userId,
- },
- chatType: "temp",
- };
- }
- }
- return {
- chatID: Number(session.userId),
- chatType: "private",
- };
- case 'group':
- return {
- chatID: Number(session.groupId),
- chatType: "group",
- };
- }
- });
- this.sendToGroup = (groupID, message) => new Promise((resolve, reject) => {
- this.enqueue('group', groupID, () => this.bot.sendMessage(groupID, message).then(resolve).catch(reject));
- });
- this.sendToUser = (userID, message) => new Promise((resolve, reject) => {
- this.enqueue('private', userID, () => this.bot.sendPrivateMessage(userID, message).then(resolve).catch(reject));
- });
- this.sendTo = (subscriber, messageChain, noErrors = false) => Promise.all((splitted => [splitted.message, ...splitted.attachments])(exports.Message.separateAttachment(messageChain)).map(msg => {
- switch (subscriber.chatType) {
- case 'group':
- return this.sendToGroup(subscriber.chatID.toString(), msg);
- case 'private':
- return this.sendToUser(subscriber.chatID.toString(), msg);
- case 'temp':
- return this.sendToUser(subscriber.chatID.qq.toString(), msg);
- }
- }))
- .then(response => {
- if (response === undefined)
- return;
- logger.info(`pushing data to ${JSON.stringify(subscriber.chatID)} was successful, response: ${response}`);
- })
- .catch(reason => {
- logger.error(exports.Message.ellipseBase64(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`));
- if (!noErrors)
- throw reason instanceof Error ? reason : Error(reason);
- });
- this.initBot = () => {
- this.app = new koishi_1.App({
- type: 'onebot',
- server: `ws://${this.botInfo.host}:${this.botInfo.port}`,
- selfId: this.botInfo.bot_id.toString(),
- token: this.botInfo.access_token,
- axiosConfig: {
- maxContentLength: Infinity,
- },
- processMessage: msg => msg.trim(),
- });
- this.app.on('friend-request', (session) => __awaiter(this, void 0, void 0, function* () {
- const userString = `${session.username}(${session.userId})`;
- let groupId;
- let groupString;
- if (session.username in this.tempSenders)
- groupId = this.tempSenders[session.userId].toString();
- logger.debug(`detected new friend request event: ${userString}`);
- return session.bot.getGroupList().then(groupList => {
- if (groupList.some(groupItem => {
- const test = groupItem.groupId === groupId;
- if (test)
- groupString = `${groupItem.groupName}(${groupId})`;
- return test;
- })) {
- return session.bot.handleFriendRequest(session.messageId, true)
- .then(() => { logger.info(`accepted friend request from ${userString} (from group ${groupString})`); })
- .catch(error => { logger.error(`error accepting friend request from ${userString}, error: ${error}`); });
- }
- (0, utils_1.chainPromises)(groupList.map(groupItem => (done) => Promise.resolve(done ||
- this.bot.getGroupMember(groupItem.groupId, session.userId).then(() => {
- groupString = `${groupItem.groupName}(${groupItem.groupId})`;
- return session.bot.handleFriendRequest(session.messageId, true)
- .then(() => { logger.info(`accepted friend request from ${userString} (found in group ${groupString})`); })
- .catch(error => { logger.error(`error accepting friend request from ${userString}, error: ${error}`); })
- .then(() => true);
- }).catch(() => false)))).then(done => {
- if (done)
- return;
- logger.warn(`received friend request from ${userString} (stranger)`);
- logger.warn('please manually accept this friend request');
- });
- });
- }));
- this.app.on('group-request', (session) => __awaiter(this, void 0, void 0, function* () {
- const userString = `${session.username}(${session.userId})`;
- const groupString = `${session.groupName}(${session.groupId})`;
- logger.debug(`detected group invitation event: ${groupString}}`);
- return session.bot.getFriendList().then(friendList => {
- if (friendList.some(friendItem => friendItem.userId = session.userId)) {
- return session.bot.handleGroupRequest(session.messageId, true)
- .then(() => { logger.info(`accepted group invitation from ${userString} (friend)`); })
- .catch(error => { logger.error(`error accepting group invitation from ${userString}, error: ${error}`); });
- }
- logger.warn(`received group invitation from ${userString} (stranger)`);
- logger.warn('please manually accept this group invitation');
- });
- }));
- this.app.middleware((session) => __awaiter(this, void 0, void 0, function* () {
- const chat = yield this.getChat(session);
- const cmdObj = (0, command_1.parseCmd)(session.content);
- const reply = (msg) => __awaiter(this, void 0, void 0, function* () {
- const userString = `${session.username}(${session.userId})`;
- return (chat.chatType === "group" ? this.sendToGroup : this.sendToUser)(chat.chatID.toString(), msg)
- .catch(error => { logger.error(`error replying to message from ${userString}, error: ${error}`); });
- });
- switch (cmdObj.cmd) {
- case 'twitter_search':
- (0, command_1.search)(chat, cmdObj.args, reply);
- break;
- case 'twitterpic_search':
- (0, command_1.picSearch)(chat, cmdObj.args, reply);
- break;
- case 'help':
- if (cmdObj.args.length === 0) {
- reply(`推特搜索机器人:
- /twitter_search〈表达式〉[参数列表...] - 进行自定义查询(详见 /help twitter_search)
- /twitterpic_search〈表达式〉[参数列表...] - 对媒体推文进行自定义查询`);
- }
- else if (cmdObj.args[0] === 'twitter_search') {
- reply(`查询时间线中的推文:
- /twitter_search〈表达式〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
- /twitterpic_search 为 /twitter_search〈表达式〉(filter:media) \
- 的简便写法
- 参数列表(方框内全部为可选,留空则为默认):
- count:查询数量上限(类型:正整数,最大值 100)[默认值:15]
- since:查询起始点(类型:正整数或日期)[默认值:(空,无限过去)]
- until:查询结束点(类型:正整数或日期)[默认值:(空,当前时刻)]`)
- .then(() => reply(`\
- 起始点和结束点为正整数时取推特推文编号作为比较基准,否则会尝试作为日期读取。
- 推荐的日期格式:2012-12-22 12:22 UTC+2(日期和时间均为可选,可分别添加)
- since 和 until 会被直接转换成 since_id 和 max_id 并覆盖表达式中同名参数,\
- 但不会覆盖表达式中原生精确到日的 since 和 until。
- 例子:/twitter_search #imas_cg_6th count=5 since="2018-12-02 \
- 13:00 UTC+9" until="2018-12-08 17:00 UTC+8"
- /twitter_search (from:mineda_mayu)(exclude:replies) \
- since="2020-12-24 00:00 UTC+8" until="2021-01-01 00:00 UTC+8"
- /twitter_search "to:hirayama8emi OR from:choucho0115 \
- filter:native_video" until="2021-05-01 UTC+8"`))
- .then(() => reply(`\
- 搜索表达式具体例子可以参考:
- https://www.labnol.org/internet/twitter-search-tricks/13693/
- https://developer.twitter.com/en/docs/twitter-api/v1/\
- rules-and-filtering/search-operators`));
- }
- }
- }), true);
- };
- this.listen = (logMsg = 'connecting to bot provider...') => __awaiter(this, void 0, void 0, function* () {
- logger.warn(logMsg);
- try {
- yield this.app.start();
- }
- catch (err) {
- logger.error(`error connecting to bot provider at ${this.app.options.server}, will retry in 2.5s...`);
- yield (0, koishi_1.sleep)(2500);
- yield this.listen('retry connecting...');
- }
- });
- this.connect = () => __awaiter(this, void 0, void 0, function* () {
- this.initBot();
- yield this.listen();
- this.bot = this.app.getBot('onebot');
- });
- logger.warn(`Initialized koishi on ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
- this.botInfo = opt;
- }
- }
- exports.default = default_1;
|