123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298 |
- "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");
- const plugin_adapter_onebot_1 = require("@koishijs/plugin-adapter-onebot");
- const command_1 = require("./command");
- const loggers_1 = require("./loggers");
- const logger = (0, loggers_1.getLogger)('qqbot');
- const batchExec = (executer, ...[chat, args, reply]) => {
- let combinedMsg = '';
- let promise = Promise.resolve();
- args.forEach(arg => {
- promise = promise.then(() => new Promise(resolve => {
- executer(chat, [arg], (msg) => {
- combinedMsg += msg + '\n';
- resolve();
- });
- }));
- });
- promise.then(() => {
- if (combinedMsg)
- reply(combinedMsg.slice(0, -1));
- });
- };
- exports.Message = {
- Image: koishi_1.segment.image,
- Video: koishi_1.segment.video,
- Voice: koishi_1.segment.audio,
- separateAttachment: (msg) => {
- const attachments = [];
- const message = msg.replace(/<(video|record) .*?\/>/g, code => {
- attachments.push(code);
- return '';
- });
- return { message, attachments };
- },
- parseCQCode: (cqStr) => plugin_adapter_onebot_1.CQCode.parse(cqStr).map(seg => {
- if (typeof seg.attrs.file === 'string') {
- seg.attrs.url = seg.attrs.file;
- delete seg.attrs.file;
- }
- return seg;
- }).join(''),
- toCQCode: (segStr) => koishi_1.segment.parse(segStr).map(seg => {
- if (typeof seg.attrs.url === 'string') {
- seg.attrs.file = seg.attrs.url;
- delete seg.attrs.url;
- }
- return (0, plugin_adapter_onebot_1.CQCode)(seg.type, seg.attrs);
- }).join(''),
- };
- 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.getSender = ({ chatID, chatType }) => (msg) => (chatType === 'guild' ? this.sendToChannel :
- chatType === 'group' ? this.sendToGroup :
- this.sendToUser)(chatID.toString(), msg);
- this.getChat = (session) => __awaiter(this, void 0, void 0, function* () {
- if (session.type !== 'message')
- return null;
- if (session.subsubtype === 'guild') {
- return {
- chatID: `${session.onebot.guild_id}:${session.onebot.channel_id}`,
- chatType: 'guild',
- };
- }
- switch (session.subtype) {
- case 'private':
- const { group_id: groupId } = session.onebot.sender;
- if (groupId) {
- const friendList = yield session.bot.getFriendList();
- if (!friendList.some(friendItem => friendItem.userId === session.userId)) {
- this.tempSenders[session.userId] = groupId;
- return {
- chatID: {
- qq: Number(session.userId),
- group: Number(groupId),
- toString: () => session.userId,
- },
- chatType: 'temp',
- };
- }
- }
- return {
- chatID: Number(session.userId),
- chatType: 'private',
- };
- case 'group':
- return {
- chatID: Number(session.guildId),
- chatType: 'group',
- };
- }
- });
- this.sendToChannel = (guildChannel, message) => new Promise((resolve, reject) => {
- const [guildID, channelID] = guildChannel.split(':');
- this.enqueue('guild', guildChannel, () => this.bot.guildBot.sendMessage(channelID, message, guildID)
- .then(([response]) => resolve(response)).catch(reject));
- });
- this.sendToGroup = (groupID, message) => new Promise((resolve, reject) => {
- this.enqueue('group', groupID, () => this.bot.sendMessage(groupID, message)
- .then(([response]) => resolve(response)).catch(reject));
- });
- this.sendToUser = (userID, message) => new Promise((resolve, reject) => {
- this.enqueue('private', userID, () => this.bot.sendPrivateMessage(userID, message)
- .then(([response]) => resolve(response)).catch(reject));
- });
- this.sendTo = (subscriber, messageChain, noErrors = false) => Promise.all((splitted => [splitted.message, ...splitted.attachments])(exports.Message.separateAttachment(messageChain)).map(this.getSender(subscriber)))
- .then(response => {
- if (response === undefined)
- return;
- logger.info(`pushing data to ${JSON.stringify(subscriber.chatID)} was successful, response: ${response}`);
- })
- .catch(reason => {
- logger.error(`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();
- this.app.plugin(plugin_adapter_onebot_1.default, this.config);
- this.app.on('friend-request', (session) => __awaiter(this, void 0, void 0, function* () {
- const userString = `${session.username}(${session.userId})`;
- logger.debug(`detected new friend request event: ${userString}`);
- try {
- const isTemp = session.username in this.tempSenders;
- const { guildId, guildName } = isTemp ?
- yield session.bot.getGuild(this.tempSenders[session.userId].toString()) :
- (yield session.bot.getGuildList()).find(({ guildId }) => __awaiter(this, void 0, void 0, function* () {
- try {
- return yield this.bot.getGuildMember(guildId, session.userId);
- }
- catch (_b) { }
- }));
- try {
- const groupString = `${guildName}(${guildId})`;
- yield session.bot.handleFriendRequest(session.messageId, true);
- logger.info(`accepted friend request from ${userString} (${isTemp ? 'from' : 'found in'} group ${groupString})`);
- }
- catch (error) {
- logger.error(`error accepting friend request from ${userString}, error: ${error}`);
- }
- }
- catch (_a) {
- logger.warn(`received friend request from ${userString} (stranger)`);
- logger.warn('please manually accept this friend request');
- }
- }));
- this.app.on('guild-request', (session) => __awaiter(this, void 0, void 0, function* () {
- const userString = `${session.username}(${session.userId})`;
- const groupString = `${session.guildName}(${session.guildId})`;
- logger.debug(`detected group invitation event: ${groupString}}`);
- const friendList = yield session.bot.getFriendList();
- if (friendList.some(friendItem => friendItem.userId = session.userId)) {
- try {
- session.bot.handleGuildRequest(session.messageId, true);
- 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);
- let userString = `${session.username}(${session.userId})`;
- if (chat.chatType === 'temp') {
- const group = yield session.bot.getGuild(chat.chatID.group.toString());
- userString += ` (from group ${group.guildName}(${group.guildId}))`;
- }
- const cmdObj = (0, command_1.parseCmd)(session.content);
- const reply = (msg) => this.getSender(chat)(msg).catch(error => {
- if (chat.chatType === 'temp') {
- return logger.info(`ignored error while replying to ${userString}`);
- }
- logger.error(`error replying to message from ${userString}, error: ${error}`);
- });
- switch (cmdObj.cmd) {
- case 'twipic_view':
- (0, command_1.view)(chat, cmdObj.args, reply);
- break;
- case 'twipic_resendlast':
- (0, command_1.resendLast)(chat, cmdObj.args, reply);
- break;
- case 'twipic_query':
- (0, command_1.query)(chat, cmdObj.args, reply);
- break;
- case 'twipic_sub':
- batchExec(this.botInfo.sub, chat, cmdObj.args, reply);
- break;
- case 'twipic_unsub':
- batchExec(this.botInfo.unsub, chat, cmdObj.args, reply);
- break;
- case 'twipic_unsuball':
- this.botInfo.unsubAll(chat, cmdObj.args, reply);
- break;
- case 'twipic_listsub':
- this.botInfo.list(chat, cmdObj.args, reply);
- break;
- case 'help':
- if (cmdObj.args[0] === 'twipic') {
- reply(`推特媒体推文搬运机器人:
- /twipic_listsub - 查询当前聊天中的媒体推文订阅
- /twipic_sub〈链接|用户名〉[〈链接|用户名〉...] - 订阅一个或多个媒体推文搬运
- /twipic_unsub〈链接|用户名〉[〈链接|用户名〉...] - 退订一个或多个媒体推文搬运
- /twipic_unsuball - 退订当前聊天中全部的媒体推文搬运
- /twipic_view〈链接|表达式〉[{force|refresh}={on|off}] - 查看推文(可选强制重新载入)
- /twipic_resendlast〈用户名〉- 强制重发该用户最后一条媒体推文
- /twipic_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twipic_query)\
- ${chat.chatType === 'temp' ?
- '\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''}`);
- }
- else if (cmdObj.args[0] === 'twipic_query') {
- reply(`查询时间线中的媒体推文:
- /twipic_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
- 参数列表(方框内全部为可选,留空则为默认):
- count:查询数量上限(类型:非零整数,最大值正负 50)[默认值:10]
- since:查询起始点(类型:正整数或日期)[默认值:(空,无限过去)]
- until:查询结束点(类型:正整数或日期)[默认值:(空,当前时刻)]
- noreps 忽略回复推文(类型:on/off)[默认值:on(是)]
- norts:忽略原生转推(类型:on/off)[默认值:off(否)]`)
- .then(() => reply(`\
- 起始点和结束点为正整数时取推特推文编号作为比较基准,否则会尝试作为日期读取。
- 推荐的日期格式:2012-12-22 12:22 UTC+2 (日期和时间均为可选,可分别添加)
- count 为正时,从新向旧查询;为负时,从旧向新查询
- count 与 since/until 并用时,取二者中实际查询结果较少者
- 例子:/twipic_query RiccaTachibana count=5 since="2019-12-30\
- UTC+9" until="2020-01-06 UTC+8" norts=on
- 从起始时间点(含)到结束时间点(不含)从新到旧获取最多 5 条媒体推文,\
- 其中不包含原生转推(实际上用户只发了 1 条)`));
- }
- }
- }), 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.config.endpoint}, 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.bots.find(bot => bot.selfId === this.config.selfId);
- });
- logger.warn(`Initialized koishi on ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
- this.botInfo = opt;
- }
- get config() {
- return {
- protocol: 'ws',
- endpoint: `ws://${this.botInfo.host}:${this.botInfo.port}`,
- selfId: this.botInfo.bot_id.toString(),
- token: this.botInfo.access_token,
- };
- }
- ;
- }
- exports.default = default_1;
|