Skip to content

Commit

Permalink
fix: 一些问题
Browse files Browse the repository at this point in the history
  • Loading branch information
clansty committed Jul 12, 2024
1 parent 3494f85 commit 4fca499
Show file tree
Hide file tree
Showing 15 changed files with 51 additions and 72 deletions.
2 changes: 0 additions & 2 deletions main/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,9 @@
"image-size": "^1.1.1",
"lodash": "^4.17.21",
"log4js": "^6.9.1",
"markdown-escape": "^2.0.0",
"nodejs-base64": "^2.0.0",
"posthog-node": "^4.0.1",
"prisma": "5.16.2",
"probe-image-size": "^7.2.3",
"prompts": "^2.4.2",
"quote-api": "https://github.com/Clansty/quote-api/archive/014b21138afbbe0e12c91b00561414b1e851fc0f.tar.gz",
"sharp": "^0.33.4",
Expand Down
3 changes: 3 additions & 0 deletions main/src/client/NapCatClient/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,9 @@ export class NapCatClient extends QQClient {
}
const message = (data.message as unknown as Receive[keyof Receive][]);
const replyNode = message.find(it => it.type === 'reply');
if (replyNode) {
message.splice(message.indexOf(replyNode), 1);
}
const replyMessage = replyNode ? await this.getMessage(replyNode.data.id) : undefined;
const event = new MessageEvent(
{ id: data.sender.user_id, card: data.sender.card, nickname: data.sender.nickname, name: data.sender.card || data.sender.nickname },
Expand Down
2 changes: 1 addition & 1 deletion main/src/client/NapCatClient/convert.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Receive, Send } from 'node-napcat-ts';
import { SendableElem } from '../QQClient';
import { MessageElem, segment } from '@icqqjs/icqq';
import { MessageElem } from '@icqqjs/icqq';

export const messageElemToNapCatSendable = (elem: SendableElem): Send[keyof Send] => {
switch (elem.type) {
Expand Down
5 changes: 2 additions & 3 deletions main/src/client/OicqClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ import { escapeXml, gzip, timestamp } from '@icqqjs/icqq/lib/common';
import { pb } from '@icqqjs/icqq/lib/core';
import env from '../models/env';
import {
CreateQQClientParamsBase, Friend, FriendIncreaseEvent, Group,
GroupMemberDecreaseEvent,
CreateQQClientParamsBase, Friend, FriendIncreaseEvent, GroupMemberDecreaseEvent,
GroupMemberIncreaseEvent,
MessageEvent, MessageRecallEvent, PokeEvent,
QQClient,
Expand Down Expand Up @@ -337,6 +336,6 @@ export default class OicqClient extends QQClient {
>${title ? `<title color="#303133" size="26">${escapeXml(title)}</title>` : ''
}<hr hidden="false" style="0" /><summary size="26" color="#777777">请谨慎查看</summary
></item><source name="Q2TG" icon="" action="" appid="-1" /></msg>`.replaceAll('\n', ''),
} as XmlElem];
} as XmlElem] as any;
}
}
4 changes: 2 additions & 2 deletions main/src/client/QQClient/entity.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import type { MessageRet, MfaceElem, Quotable, Sendable } from '@icqqjs/icqq';
import type { MessageRet, MfaceElem, Quotable } from '@icqqjs/icqq';
import { Gender, GroupRole } from '@icqqjs/icqq/lib/common';
import { AtElem, FaceElem, ImageElem, PttElem, TextElem, VideoElem } from '@icqqjs/icqq/lib/message/elements';
import type { Receive } from 'node-napcat-ts';

// 全平台支持的 Elem
export type SendableElem = TextElem | FaceElem | ImageElem | AtElem | PttElem | VideoElem | MfaceElem;
export type Sendable = SendableElem | string | (SendableElem | string)[];

export interface QQEntity {
readonly client: { uin: number };
Expand Down
4 changes: 2 additions & 2 deletions main/src/client/QQClient/events.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Friend, Group } from './index';
import type { Sendable, MessageElem } from '@icqqjs/icqq';
import { Friend, Group, Sendable } from './index';
import type { MessageElem } from '@icqqjs/icqq';
import type { Receive } from 'node-napcat-ts';

export abstract class ChatEvent {
Expand Down
8 changes: 4 additions & 4 deletions main/src/client/QQClient/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { CreateOicqParams } from '../OicqClient';
import { Friend, Group } from './entity';
import { Friend, Group, SendableElem } from './entity';
import {
FriendIncreaseEvent,
GroupMemberDecreaseEvent,
GroupMemberIncreaseEvent,
MessageEvent,
MessageRecallEvent, PokeEvent,
} from './events';
import type { FriendRequestEvent, GroupInviteEvent, ImageElem, MessageElem } from '@icqqjs/icqq';
import type { FriendRequestEvent, GroupInviteEvent, ImageElem } from '@icqqjs/icqq';
import { CreateNapCatParams } from '../NapCatClient';

export * from './events';
Expand Down Expand Up @@ -187,8 +187,8 @@ export abstract class QQClient {

public abstract pickGroup(groupId: number): Promise<Group>;

public async createSpoilerImageEndpoint(image: ImageElem, nickname: string, title?: string): Promise<MessageElem[]> {
const res: MessageElem[] = [
public async createSpoilerImageEndpoint(image: ImageElem, nickname: string, title?: string): Promise<SendableElem[]> {
const res: SendableElem[] = [
{
type: 'text',
text: '[Spoiler 图片]',
Expand Down
2 changes: 1 addition & 1 deletion main/src/constants/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ enum flags {
RICH_HEADER = 1 << 7,
NO_QUOTE_PIN = 1 << 8,
NO_FORWARD_OTHER_BOT = 1 << 9,
USE_MARKDOWN = 1 << 10,
// USE_MARKDOWN = 1 << 10,
DISABLE_SEAMLESS = 1 << 11,
NO_FLASH_PIC = 1 << 12,
DISABLE_SLASH_COMMAND = 1 << 13,
Expand Down
3 changes: 1 addition & 2 deletions main/src/controllers/ForwardController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@ import {
PokeEvent,
Friend,
Group,
GroupMemberInfo,

} from '../client/QQClient';
import { Member as OicqGroupMember } from '@icqqjs/icqq';
import posthog from '../models/posthog';

export default class ForwardController {
Expand Down
4 changes: 2 additions & 2 deletions main/src/controllers/HugController.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import Instance from '../models/Instance';
import Telegram from '../client/Telegram';
import { AtElem, Sendable } from '@icqqjs/icqq';
import { AtElem } from '@icqqjs/icqq';
import { Pair } from '../models/Pair';
import { Api } from 'telegram';
import db from '../models/db';
import BigInteger from 'big-integer';
import helper from '../helpers/forwardHelper';
import { getLogger, Logger } from 'log4js';
import flags from '../constants/flags';
import { MessageEvent, QQClient, Group, GroupMemberInfo } from '../client/QQClient';
import { MessageEvent, QQClient, Group, GroupMemberInfo, Sendable } from '../client/QQClient';
import { Member as OicqMember } from '@icqqjs/icqq/lib/member';

type ActionSubjectTg = {
Expand Down
2 changes: 1 addition & 1 deletion main/src/controllers/InChatCommandsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import Telegram from '../client/Telegram';
import { Api } from 'telegram';
import flags from '../constants/flags';
import { editFlags } from '../utils/flagControl';
import { QQClient, Group } from '../client/QQClient';
import { QQClient } from '../client/QQClient';

export default class InChatCommandsController {
private readonly service: InChatCommandsService;
Expand Down
2 changes: 1 addition & 1 deletion main/src/controllers/QuotLyController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import convert from '../helpers/convert';
import { Pair } from '../models/Pair';
import env from '../models/env';
import flags from '../constants/flags';
import { MessageEvent, QQClient, Group } from '../client/QQClient';
import { MessageEvent, QQClient } from '../client/QQClient';
import posthog from '../models/posthog';

export default class {
Expand Down
2 changes: 2 additions & 0 deletions main/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import db from './models/db';
import api from './api';
import env from './models/env';
import posthog from './models/posthog';
import OicqClient from './client/OicqClient';

(async () => {
configure({
Expand Down Expand Up @@ -43,6 +44,7 @@ import posthog from './models/posthog';

setTimeout(async () => {
for (const instance of Instance.instances.filter(it => it.workMode === 'group')) {
if (!(instance.oicq instanceof OicqClient)) continue;
try {
await instance.forwardPairs.initMapInstance(Instance.instances.filter(it => it.workMode === 'personal'));
}
Expand Down
3 changes: 2 additions & 1 deletion main/src/models/ForwardPairs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { BigInteger } from 'big-integer';
import { Pair } from './Pair';
import { getLogger, Logger } from 'log4js';
import Instance from './Instance';
import posthog from './posthog';
import OicqClient from '../client/OicqClient';

export default class ForwardPairs {
private pairs: Pair[] = [];
Expand Down Expand Up @@ -81,6 +81,7 @@ export default class ForwardPairs {
public async initMapInstance(instances: Instance[]) {
for (const forwardPair of this.pairs) {
for (const instance of instances) {
if(!(instance.oicq instanceof OicqClient)) continue;
const instanceTgUserId = instance.userMe.id.toString();
if (forwardPair.instanceMapForTg[instanceTgUserId]) continue;
try {
Expand Down
77 changes: 27 additions & 50 deletions main/src/services/ForwardService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ import {
FaceElem,
Group as OicqGroup,
Friend as OicqFriend,
MessageElem, PttElem,
PttElem,
Quotable,
segment,
Sendable,
} from '@icqqjs/icqq';
import { fetchFile, getBigFaceUrl, getImageUrlByMd5, isContainsUrl } from '../utils/urls';
import { ButtonLike, FileLike } from 'telegram/define';
Expand Down Expand Up @@ -40,10 +39,8 @@ import env from '../models/env';
import { CustomFile } from 'telegram/client/uploads';
import flags from '../constants/flags';
import BigInteger from 'big-integer';
import probe from 'probe-image-size';
import markdownEscape from 'markdown-escape';
import pastebin from '../utils/pastebin';
import { MessageEvent, QQClient } from '../client/QQClient';
import { MessageEvent, QQClient, Sendable, SendableElem } from '../client/QQClient';
import posthog from '../models/posthog';

const NOT_CHAINABLE_ELEMENTS = ['flash', 'record', 'video', 'location', 'share', 'json', 'xml', 'poke'];
Expand Down Expand Up @@ -532,8 +529,7 @@ export default class ForwardService {
public async forwardFromTelegram(message: Api.Message, pair: Pair): Promise<Array<QQMessageSent>> {
try {
const tempFiles: FileResult[] = [];
let chain: (string | MessageElem)[] = [];
let markdown: string[] = [], markdownCompatible = true;
let chain: (string | SendableElem)[] = [];
const senderId = Number(message.senderId || message.sender?.id);
// 这条消息在 tg 中被回复的时候显示的
let brief = '', isSpoilerPhoto = false;
Expand All @@ -543,30 +539,19 @@ export default class ForwardService {
(message.fwdFrom?.fromName ||
helper.getUserDisplayName(await message.forward.getChat() || await message.forward.getSender())) :
'');
markdown.push(`![头像 #30px#30px](${helper.generateTelegramAvatarUrl(this.instance.id, senderId)}) **${messageHeader}**`);
messageHeader += ': \n';
if ((pair.flags | this.instance.flags) & flags.COLOR_EMOJI_PREFIX) {
messageHeader = emoji.tgColor((message.sender as Api.User)?.color?.color || message.senderId.toJSNumber()) + messageHeader;
}

const useImage = (image: Buffer, asface: boolean) => {
const md5 = md5Hex(image);
const dimensions = probe.sync(image);
let width = dimensions.width;
let height = dimensions.height;
if (asface) {
width /= 2;
height /= 2;
}
markdown.push(`![image #${width}px#${height}px](${getImageUrlByMd5(md5)})`);
chain.push({
type: 'image',
file: image,
asface,
});
};
const useText = (text: string) => {
markdown.push(markdownEscape(text));
chain.push(text);
};

Expand All @@ -583,7 +568,6 @@ export default class ForwardService {
}, messageHeader.substring(0, messageHeader.length - 3), message.message));

brief += '[Spoiler 图片]';
markdownCompatible = false;
}
else {
useImage(await message.downloadMedia({}) as Buffer, !!message.sticker);
Expand All @@ -598,16 +582,13 @@ export default class ForwardService {
else if (file.mimeType === 'video/webm' || message.gif) {
// 把 webm 转换成 gif
const convertedPath = await convert.webm2gif(message.document.id.toString(16), () => message.downloadMedia({}));
// markdown 里的 gif 不能动
markdownCompatible = false;
useImage(await fsP.readFile(convertedPath), true);
}
else {
const temp = await createTempFile();
tempFiles.push(temp);
await fsP.writeFile(temp.path, await message.downloadMedia({}));
chain.push(segment.video(temp.path));
markdownCompatible = false;
}
brief += '[视频]';
}
Expand All @@ -621,7 +602,6 @@ export default class ForwardService {
const gifPath = await convert.tgs2gif(message.sticker.id.toString(16), () => message.downloadMedia({}));
useImage(await fsP.readFile(gifPath), true);
}
markdownCompatible = false;
brief += '[贴纸]';
}
else if (message.voice) {
Expand All @@ -630,7 +610,6 @@ export default class ForwardService {
await fsP.writeFile(temp.path, await message.downloadMedia({}));
const bufSilk = await silk.encode(temp.path);
chain.push(segment.record(bufSilk));
markdownCompatible = false;
if (this.speechClient) {
const pcmPath = await createTempFile({ postfix: '.pcm' });
tempFiles.push(pcmPath);
Expand Down Expand Up @@ -666,16 +645,24 @@ export default class ForwardService {
else if (message.venue && message.venue.geo instanceof Api.GeoPoint) {
// 地标
const geo: { lat: number, lng: number } = eviltransform.wgs2gcj(message.venue.geo.lat, message.venue.geo.long);
chain.push(segment.location(geo.lat, geo.lng, `${message.venue.title} (${message.venue.address})`));
if (this.oicq instanceof OicqGroup || this.oicq instanceof OicqFriend) {
chain.push(segment.location(geo.lat, geo.lng, `${message.venue.title} (${message.venue.address})`) as any);
}
else {
chain.push(`[位置:${message.venue.title} (${message.venue.address})]`);
}
brief += `[位置:${message.venue.title}]`;
markdownCompatible = false;
}
else if (message.geo instanceof Api.GeoPoint) {
// 普通的位置,没有名字
const geo: { lat: number, lng: number } = eviltransform.wgs2gcj(message.geo.lat, message.geo.long);
chain.push(segment.location(geo.lat, geo.lng, '选中的位置'));
if (this.oicq instanceof OicqGroup || this.oicq instanceof OicqFriend) {
chain.push(segment.location(geo.lat, geo.lng, '选中的位置') as any);
}
else {
chain.push(`[位置:${geo.lat} ${geo.lng}]\nhttps://uri.amap.com/marker?position=${geo.lng},${geo.lat}`);
}
brief += '[位置]';
markdownCompatible = false;
}
else if (message.media instanceof Api.MessageMediaDocument && message.media.document instanceof Api.Document) {
const file = message.media.document;
Expand Down Expand Up @@ -709,7 +696,7 @@ export default class ForwardService {
const emojiEntities = (message.entities || []).filter(it => it instanceof Api.MessageEntityCustomEmoji) as Api.MessageEntityCustomEmoji[];
if (emojiEntities.length) {
const isMessageAllEmojis = _.sum(emojiEntities.map(it => it.length)) === message.message.length;
const newChain = [] as (string | MessageElem)[];
const newChain = [] as (string | SendableElem)[];
let messageLeft = message.message;
for (let i = emojiEntities.length - 1; i >= 0; i--) {
newChain.unshift(messageLeft.substring(emojiEntities[i].offset + emojiEntities[i].length));
Expand All @@ -724,7 +711,6 @@ export default class ForwardService {
}
chain.push(messageLeft, ...newChain);
brief += message.message;
markdown.push(markdownEscape(message.message));
}
// Q2TG Bot 转发的消息目前不会包含 custom emoji
else if (message.forward?.senderId?.eq?.(this.tgBot.me.id) && /^.*: ?$/.test(message.message.split('\n')[0])) {
Expand All @@ -746,7 +732,6 @@ export default class ForwardService {
// 处理回复
let source: Quotable;
if (message.replyToMsgId || message.replyTo) {
markdownCompatible = false;
try {
console.log(message.replyTo);
const quote = message.replyToMsgId && await db.message.findFirst({
Expand Down Expand Up @@ -813,7 +798,8 @@ export default class ForwardService {
eqq: { type: 'tg', tgUid: senderId, noSplitSender: true, version: 2 },
q2tgSkip: true,
}, undefined, 0),
},
// 能启用无缝模式一定是 icqq 而不是 NapCat
} as any,
], source);
tempFiles.forEach(it => it.cleanup());
return [{
Expand All @@ -830,28 +816,19 @@ export default class ForwardService {

if (this.instance.workMode === 'group' && !isSpoilerPhoto) {
chainableElements.unshift(messageHeader);
if (markdownCompatible && (pair.flags | this.instance.flags) & flags.USE_MARKDOWN) {
chainableElements.push({
type: 'markdown',
content: markdown.join('\n'),
});
}
}
const qqMessages = [] as Array<QQMessageSent>;
if (chainableElements.length) {
chainableElements.push({
type: 'mirai',
data: JSON.stringify({
id: senderId,
eqq: { type: 'tg', tgUid: senderId, noSplitSender: this.instance.workMode === 'personal', version: 2 },
}, undefined, 0),
});
let messageToSend: Sendable = chainableElements;
if (chainableElements.some(it => typeof it === 'object' && it.type === 'markdown')) {
this.log.debug(chainableElements);
throw new Error('markdown 早寄了');
// messageToSend = await pair.qq.uploadLongMsg(chainableElements);
if (this.oicq instanceof OicqGroup || this.oicq instanceof OicqFriend) {
chainableElements.push({
type: 'mirai',
data: JSON.stringify({
id: senderId,
eqq: { type: 'tg', tgUid: senderId, noSplitSender: this.instance.workMode === 'personal', version: 2 },
}, undefined, 0),
} as any);
}
let messageToSend: Sendable = chainableElements;
qqMessages.push({
...await pair.qq.sendMsg(messageToSend, source),
brief,
Expand Down

0 comments on commit 4fca499

Please sign in to comment.