|
@@ -1,6 +1,5 @@
|
|
|
-import { App, Bot, segment, Session, sleep } from 'koishi';
|
|
|
-import 'koishi-adapter-onebot';
|
|
|
-import { Message as CQMessage, SenderInfo } from 'koishi-adapter-onebot';
|
|
|
+import { App, segment, Session, sleep } from 'koishi';
|
|
|
+import onebot, { WsClient, OneBotBot, CQCode } from '@koishijs/plugin-adapter-onebot';
|
|
|
|
|
|
import { parseCmd, query, view, resendLast } from './command';
|
|
|
import { getLogger } from './loggers';
|
|
@@ -8,8 +7,6 @@ import { chainPromises } from './utils';
|
|
|
|
|
|
const logger = getLogger('qqbot');
|
|
|
|
|
|
-type CQSession = Session & CQMessage & {sender: SenderInfo & {groupId?: number}};
|
|
|
-
|
|
|
interface IQQProps {
|
|
|
access_token: string;
|
|
|
host: string;
|
|
@@ -21,35 +18,53 @@ interface IQQProps {
|
|
|
unsubAll(chat: IChat, args: string[], replyfn: (msg: string) => any): void;
|
|
|
}
|
|
|
|
|
|
-const cqUrlFix = (factory: segment.Factory<string | ArrayBuffer | Buffer>) =>
|
|
|
- (...args: Parameters<typeof factory>) =>
|
|
|
- factory(...args).replace(/(?<=\[CQ:.*)url=(?=(base64|file|https?):\/\/)/, 'file=');
|
|
|
-
|
|
|
export const Message = {
|
|
|
- Image: cqUrlFix(segment.image),
|
|
|
- Video: cqUrlFix(segment.video),
|
|
|
- Voice: cqUrlFix(segment.audio),
|
|
|
- ellipseBase64: (msg: string) => msg.replace(/(?<=\[CQ:.*base64:\/\/).*?(,|\])/g, '...$1'),
|
|
|
+ Image: segment.image,
|
|
|
+ Video: segment.video,
|
|
|
+ Voice: segment.audio,
|
|
|
separateAttachment: (msg: string) => {
|
|
|
const attachments: string[] = [];
|
|
|
- const message = msg.replace(/\[CQ:(video|record),.*?\]/g, code => {
|
|
|
+ const message = msg.replace(/<(video|record) *?\/>/g, code => {
|
|
|
attachments.push(code);
|
|
|
return '';
|
|
|
});
|
|
|
return {message, attachments};
|
|
|
},
|
|
|
+ parseCQCode: (cqStr: string) => 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: string) => segment.parse(segStr).map(seg => {
|
|
|
+ if (typeof seg.attrs.url === 'string') {
|
|
|
+ seg.attrs.file = seg.attrs.url;
|
|
|
+ delete seg.attrs.url;
|
|
|
+ }
|
|
|
+ return CQCode(seg.type, seg.attrs);
|
|
|
+ }).join(''),
|
|
|
};
|
|
|
|
|
|
export default class {
|
|
|
|
|
|
private botInfo: IQQProps;
|
|
|
private app: App;
|
|
|
- public bot: Bot;
|
|
|
+ public bot: OneBotBot;
|
|
|
|
|
|
private messageQueues: {[key: string]: (() => Promise<void>)[]} = {};
|
|
|
private tempSenders: {[key: number]: number} = {};
|
|
|
|
|
|
- private next = (type: 'private' | 'group', id: string) => {
|
|
|
+ private get config(): onebot.Config & WsClient.Config {
|
|
|
+ return {
|
|
|
+ protocol: 'ws',
|
|
|
+ endpoint: `ws://${this.botInfo.host}:${this.botInfo.port}`,
|
|
|
+ selfId: this.botInfo.bot_id.toString(),
|
|
|
+ token: this.botInfo.access_token,
|
|
|
+ };
|
|
|
+ };
|
|
|
+
|
|
|
+ private next = (type: ChatType, id: string) => {
|
|
|
const queue = this.messageQueues[`${type}:${id}`];
|
|
|
if (queue && queue.length) {
|
|
|
queue[0]().then(() => {
|
|
@@ -60,7 +75,7 @@ export default class {
|
|
|
}
|
|
|
};
|
|
|
|
|
|
- private enqueue = (type: 'private' | 'group', id: string, resolver: () => Promise<void>) => {
|
|
|
+ private enqueue = (type: ChatType, id: string, resolver: () => Promise<void>) => {
|
|
|
let wasEmpty = false;
|
|
|
const queue = this.messageQueues[`${type}:${id}`] ||= (() => { wasEmpty = true; return []; })();
|
|
|
queue.push(() => sleep(200).then(resolver));
|
|
@@ -68,76 +83,88 @@ export default class {
|
|
|
if (wasEmpty) this.next(type, id);
|
|
|
};
|
|
|
|
|
|
- private getChat = async (session: CQSession): Promise<IChat> => {
|
|
|
+ private getSender = ({chatID, chatType}: IChat) =>
|
|
|
+ (msg: string) => (
|
|
|
+ chatType === 'guild' ? this.sendToChannel :
|
|
|
+ chatType === 'group' ? this.sendToGroup :
|
|
|
+ this.sendToUser
|
|
|
+ )(chatID.toString(), msg);
|
|
|
+
|
|
|
+ private getChat = async (session: Session): Promise<IChat> => {
|
|
|
+ if (session.type !== 'message') return null;
|
|
|
+ if (session.subsubtype === 'guild') {
|
|
|
+ const channel = session.onebot.channel_id;
|
|
|
+ const guild = session.onebot.guild_id;
|
|
|
+ return {
|
|
|
+ chatID: {
|
|
|
+ channel,
|
|
|
+ guild,
|
|
|
+ toString: () => `${guild}:${channel}`,
|
|
|
+ },
|
|
|
+ chatType: 'guild',
|
|
|
+ };
|
|
|
+ }
|
|
|
switch (session.subtype) {
|
|
|
case 'private':
|
|
|
- if (session.sender.groupId) { // temp message
|
|
|
+ const {group_id: groupId} = session.onebot.sender as any;
|
|
|
+ if (groupId) { // temp message
|
|
|
const friendList = await session.bot.getFriendList();
|
|
|
if (!friendList.some(friendItem => friendItem.userId === session.userId)) {
|
|
|
- this.tempSenders[session.userId] = session.sender.groupId;
|
|
|
+ this.tempSenders[session.userId] = groupId;
|
|
|
return {
|
|
|
chatID: {
|
|
|
qq: Number(session.userId),
|
|
|
- group: Number(session.sender.groupId),
|
|
|
+ group: Number(groupId),
|
|
|
toString: () => session.userId,
|
|
|
},
|
|
|
- chatType: ChatType.Temp,
|
|
|
+ chatType: 'temp',
|
|
|
};
|
|
|
}
|
|
|
}
|
|
|
return { // already befriended
|
|
|
chatID: Number(session.userId),
|
|
|
- chatType: ChatType.Private,
|
|
|
+ chatType: 'private',
|
|
|
};
|
|
|
case 'group':
|
|
|
return {
|
|
|
- chatID: Number(session.groupId),
|
|
|
- chatType: ChatType.Group,
|
|
|
+ chatID: Number(session.guildId),
|
|
|
+ chatType: 'group',
|
|
|
};
|
|
|
}
|
|
|
};
|
|
|
|
|
|
+ private sendToChannel = (guildChannel: string, message: string) => new Promise<string>((resolve, reject) => {
|
|
|
+ const [guildID, channelID] = guildChannel.split(':');
|
|
|
+ this.enqueue('guild', guildChannel, () => this.bot.guildBot.sendMessage(channelID, message, guildID)
|
|
|
+ .then(([response]) => resolve(response)).catch(reject));
|
|
|
+ });
|
|
|
+
|
|
|
private sendToGroup = (groupID: string, message: string) => new Promise<string>((resolve, reject) => {
|
|
|
- this.enqueue('group', groupID, () => this.bot.sendMessage(groupID, message).then(resolve).catch(reject));
|
|
|
+ this.enqueue('group', groupID, () => this.bot.sendMessage(groupID, message)
|
|
|
+ .then(([response]) => resolve(response)).catch(reject));
|
|
|
});
|
|
|
|
|
|
private sendToUser = (userID: string, message: string) => new Promise<string>((resolve, reject) => {
|
|
|
- this.enqueue('private', userID, () => this.bot.sendPrivateMessage(userID, message).then(resolve).catch(reject));
|
|
|
+ this.enqueue('private', userID, () => this.bot.sendPrivateMessage(userID, message)
|
|
|
+ .then(([response]) => resolve(response)).catch(reject));
|
|
|
});
|
|
|
|
|
|
public sendTo = (subscriber: IChat, messageChain: string, noErrors = false) => Promise.all(
|
|
|
(splitted => [splitted.message, ...splitted.attachments])(
|
|
|
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': // currently unable to open session, awaiting OneBot v12
|
|
|
- return this.sendToUser(subscriber.chatID.qq.toString(), msg);
|
|
|
- }
|
|
|
- }))
|
|
|
+ ).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(Message.ellipseBase64(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`));
|
|
|
+ logger.error(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`);
|
|
|
if (!noErrors) throw reason instanceof Error ? reason : Error(reason);
|
|
|
});
|
|
|
|
|
|
private initBot = () => {
|
|
|
- this.app = new 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 = new App();
|
|
|
+ this.app.plugin(onebot, this.config);
|
|
|
|
|
|
this.app.on('friend-request', async session => {
|
|
|
const userString = `${session.username}(${session.userId})`;
|
|
@@ -145,10 +172,10 @@ export default class {
|
|
|
let groupString: string;
|
|
|
if (session.username in this.tempSenders) groupId = this.tempSenders[session.userId as unknown as number].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 session.bot.getGuildList().then(groupList => {
|
|
|
+ if (groupList.some(({guildName, guildId}) => {
|
|
|
+ const test = guildId.toString() === groupId;
|
|
|
+ if (test) groupString = `${guildName}(${guildId})`;
|
|
|
return test;
|
|
|
})) {
|
|
|
return session.bot.handleFriendRequest(session.messageId, true)
|
|
@@ -157,8 +184,8 @@ export default class {
|
|
|
}
|
|
|
chainPromises(groupList.map(groupItem =>
|
|
|
(done: boolean) => Promise.resolve(done ||
|
|
|
- this.bot.getGroupMember(groupItem.groupId, session.userId).then(() => {
|
|
|
- groupString = `${groupItem.groupName}(${groupItem.groupId})`;
|
|
|
+ this.bot.getGuildMember(groupItem.guildId, session.userId).then(() => {
|
|
|
+ groupString = `${groupItem.guildName}(${groupItem.guildName})`;
|
|
|
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}`); })
|
|
@@ -173,13 +200,13 @@ export default class {
|
|
|
});
|
|
|
});
|
|
|
|
|
|
- this.app.on('group-request', async session => {
|
|
|
+ this.app.on('guild-request', async session => {
|
|
|
const userString = `${session.username}(${session.userId})`;
|
|
|
- const groupString = `${session.groupName}(${session.groupId})`;
|
|
|
+ const groupString = `${session.guildName}(${session.guildId})`;
|
|
|
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)
|
|
|
+ return session.bot.handleGuildRequest(session.messageId, true)
|
|
|
.then(() => { logger.info(`accepted group invitation from ${userString} (friend)`); })
|
|
|
.catch(error => { logger.error(`error accepting group invitation from ${userString}, error: ${error}`); });
|
|
|
}
|
|
@@ -188,57 +215,49 @@ export default class {
|
|
|
});
|
|
|
});
|
|
|
|
|
|
- this.app.middleware(async (session: CQSession) => {
|
|
|
+ this.app.middleware(async (session: Session) => {
|
|
|
const chat = await this.getChat(session);
|
|
|
const cmdObj = parseCmd(session.content);
|
|
|
- const reply = async msg => {
|
|
|
- const userString = `${session.username}(${session.userId})`;
|
|
|
- return (chat.chatType === ChatType.Group ? this.sendToGroup : this.sendToUser)(chat.chatID.toString(), msg)
|
|
|
- .catch(error => { logger.error(`error replying to message from ${userString}, error: ${error}`); });
|
|
|
- };
|
|
|
+ const reply = (msg: string) => this.getSender(chat)(msg).catch(error => {
|
|
|
+ logger.error(`error replying to message from ${session.username}(${session.userId}), error: ${error}`);
|
|
|
+ });
|
|
|
switch (cmdObj.cmd) {
|
|
|
- case 'twitter_view':
|
|
|
- case 'twitter_get':
|
|
|
+ case 'twi_view':
|
|
|
view(chat, cmdObj.args, reply);
|
|
|
break;
|
|
|
- case 'twitter_resendlast':
|
|
|
+ case 'twi_resendlast':
|
|
|
resendLast(chat, cmdObj.args, reply);
|
|
|
break;
|
|
|
- case 'twitter_query':
|
|
|
- case 'twitter_gettimeline':
|
|
|
+ case 'twi_query':
|
|
|
query(chat, cmdObj.args, reply);
|
|
|
break;
|
|
|
- case 'twitter_sub':
|
|
|
- case 'twitter_subscribe':
|
|
|
+ case 'twi_sub':
|
|
|
this.botInfo.sub(chat, cmdObj.args, reply);
|
|
|
break;
|
|
|
- case 'twitter_unsub':
|
|
|
- case 'twitter_unsubscribe':
|
|
|
+ case 'twi_unsub':
|
|
|
this.botInfo.unsub(chat, cmdObj.args, reply);
|
|
|
break;
|
|
|
- case 'twitter_unsuball':
|
|
|
- case 'bye':
|
|
|
+ case 'twi_unsuball':
|
|
|
this.botInfo.unsubAll(chat, cmdObj.args, reply);
|
|
|
break;
|
|
|
- case 'ping':
|
|
|
- case 'twitter':
|
|
|
+ case 'twi_listsub':
|
|
|
this.botInfo.list(chat, cmdObj.args, reply);
|
|
|
break;
|
|
|
case 'help':
|
|
|
- if (cmdObj.args.length === 0) {
|
|
|
+ if (cmdObj.args[0] === 'twi') {
|
|
|
reply(`推特搬运机器人:
|
|
|
-/twitter - 查询当前聊天中的推文订阅
|
|
|
-/twitter_sub[scribe]〈链接|用户名〉- 订阅 Twitter 推文搬运
|
|
|
-/twitter_unsub[scribe]〈链接|用户名〉- 退订 Twitter 推文搬运
|
|
|
-/twitter_view〈链接|表达式〉[{force|refresh}={on|off}] - 查看推文(可选强制重新载入)
|
|
|
-/twitter_resendlast〈用户名〉- 强制重发该用户最后一条推文
|
|
|
-/twitter_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twitter_query)\
|
|
|
-${chat.chatType === ChatType.Temp ?
|
|
|
+/twi_listsub - 查询当前聊天中的推文订阅
|
|
|
+/twi_sub〈链接|用户名〉- 订阅 Twitter 推文搬运
|
|
|
+/twi_unsub〈链接|用户名〉- 退订 Twitter 推文搬运
|
|
|
+/twi_view〈链接|表达式〉[{force|refresh}={on|off}] - 查看推文(可选强制重新载入)
|
|
|
+/twi_resendlast〈用户名〉- 强制重发该用户最后一条推文
|
|
|
+/twi_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twi_query)\
|
|
|
+${chat.chatType === 'temp' ?
|
|
|
'\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''
|
|
|
}`);
|
|
|
- } else if (cmdObj.args[0] === 'twitter_query') {
|
|
|
+ } else if (cmdObj.args[0] === 'twi_query') {
|
|
|
reply(`查询时间线中的推文:
|
|
|
-/twitter_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
|
|
|
+/twi_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
|
|
|
|
|
|
参数列表(方框内全部为可选,留空则为默认):
|
|
|
count:查询数量上限(类型:非零整数,最大值正负 50)[默认值:10]
|
|
@@ -251,7 +270,7 @@ ${chat.chatType === ChatType.Temp ?
|
|
|
推荐的日期格式:2012-12-22 12:22 UTC+2 (日期和时间均为可选,可分别添加)
|
|
|
count 为正时,从新向旧查询;为负时,从旧向新查询
|
|
|
count 与 since/until 并用时,取二者中实际查询结果较少者
|
|
|
-例子:/twitter_query RiccaTachibana count=5 since="2019-12-30\
|
|
|
+例子:/twi_query RiccaTachibana count=5 since="2019-12-30\
|
|
|
UTC+9" until="2020-01-06 UTC+8" norts=on
|
|
|
从起始时间点(含)到结束时间点(不含)从新到旧获取最多 5 条推文,\
|
|
|
其中不包含原生转推(实际上用户只发了 1 条)`)
|
|
@@ -266,7 +285,7 @@ count 与 since/until 并用时,取二者中实际查询结果较少者
|
|
|
try {
|
|
|
await this.app.start();
|
|
|
} catch (err) {
|
|
|
- logger.error(`error connecting to bot provider at ${this.app.options.server}, will retry in 2.5s...`);
|
|
|
+ logger.error(`error connecting to bot provider at ${this.config.endpoint}, will retry in 2.5s...`);
|
|
|
await sleep(2500);
|
|
|
await this.listen('retry connecting...');
|
|
|
}
|
|
@@ -275,7 +294,7 @@ count 与 since/until 并用时,取二者中实际查询结果较少者
|
|
|
public connect = async () => {
|
|
|
this.initBot();
|
|
|
await this.listen();
|
|
|
- this.bot = this.app.getBot('onebot');
|
|
|
+ this.bot = this.app.bots.find(bot => bot.selfId === this.config.selfId) as OneBotBot;
|
|
|
};
|
|
|
|
|
|
constructor(opt: IQQProps) {
|