feat: support for fake forward message

This commit is contained in:
idranme 2024-10-23 18:18:05 +08:00
parent 8b04833a6a
commit c9e39769dd
No known key found for this signature in database
GPG Key ID: D0F3677546E6ECD5
17 changed files with 8854 additions and 956 deletions

View File

@ -12,7 +12,7 @@
"deploy-win": "cmd /c \"xcopy /C /S /Y dist\\* %LITELOADERQQNT_PROFILE%\\plugins\\LLOneBot\\\"",
"format": "prettier -cw .",
"check": "tsc",
"compile:proto": "pbjs --no-create --no-convert --no-encode --no-verify -t static-module -w es6 -p src/ntqqapi/proto -o src/ntqqapi/proto/compiled.js systemMessage.proto profileLikeTip.proto groupMemberChange.proto && pbts -o src/ntqqapi/proto/compiled.d.ts src/ntqqapi/proto/compiled.js"
"compile:proto": "pbjs --no-create --no-convert --no-verify -t static-module -w es6 -p src/ntqqapi/proto -o src/ntqqapi/proto/compiled.js profileLikeTip.proto groupMemberChange.proto message.proto richMedia.proto && pbts -o src/ntqqapi/proto/compiled.d.ts src/ntqqapi/proto/compiled.js"
},
"author": "",
"license": "MIT",
@ -25,7 +25,6 @@
"cors": "^2.8.5",
"cosmokit": "^1.6.3",
"express": "^5.0.1",
"fast-xml-parser": "^4.5.0",
"fluent-ffmpeg": "^2.1.3",
"minato": "^3.6.0",
"protobufjs": "^7.4.0",
@ -46,5 +45,5 @@
"vite": "^5.4.9",
"vite-plugin-cp": "^4.0.8"
},
"packageManager": "yarn@4.5.0"
"packageManager": "yarn@4.5.1"
}

View File

@ -16,7 +16,7 @@ import path from 'node:path'
import { existsSync } from 'node:fs'
import { ReceiveCmdS } from '../hook'
import { RkeyManager } from '@/ntqqapi/helper/rkey'
import { RichMediaDownloadCompleteNotify, Peer } from '@/ntqqapi/types/msg'
import { RichMediaDownloadCompleteNotify, RichMediaUploadCompleteNotify, RMBizType, Peer } from '@/ntqqapi/types/msg'
import { calculateFileMD5 } from '@/common/utils/file'
import { copyFile, stat, unlink } from 'node:fs/promises'
import { Time } from 'cosmokit'
@ -211,6 +211,28 @@ export class NTQQFileApi extends Service {
]
)
}
async uploadRMFileWithoutMsg(filePath: string, bizType: RMBizType, peerUid: string) {
const data = await invoke<{
notifyInfo: RichMediaUploadCompleteNotify
}>(
'nodeIKernelRichMediaService/uploadRMFileWithoutMsg',
[{
params: {
filePath,
bizType,
peerUid,
useNTV2: true
}
}],
{
cbCmd: ReceiveCmdS.MEDIA_UPLOAD_COMPLETE,
cmdCB: payload => payload.notifyInfo.filePath === filePath,
timeout: 10 * Time.second,
}
)
return data.notifyInfo
}
}
export class NTQQFileCacheApi extends Service {

View File

@ -3,11 +3,15 @@ import { Dict } from 'cosmokit'
import { getBuildVersion } from '@/common/utils/misc'
import { TEMP_DIR } from '@/common/globalVars'
import { copyFile } from 'fs/promises'
import { ChatType, Peer } from '../types'
import path from 'node:path'
import addon from './external/crychic-win32-x64.node?asset'
export class Native {
public activated = false
private crychic?: Dict
private seq = 0
private cb: Map<number, Function> = new Map()
constructor(private ctx: Context) {
ctx.on('ready', () => {
@ -35,6 +39,11 @@ export class Native {
if (!this.checkVersion()) {
return
}
const handler = async (name: string, ...e: unknown[]) => {
if (name === 'cb') {
this.cb.get(e[0] as number)?.(e[1])
}
}
try {
const fileName = path.basename(addon)
const dest = path.join(TEMP_DIR, fileName)
@ -45,7 +54,9 @@ export class Native {
this.ctx.logger.warn(e)
}
this.crychic = require(dest)
this.crychic!.setCryHandler(handler)
this.crychic!.init()
this.activated = true
} catch (e) {
this.ctx.logger.warn('crychic 加载失败', e)
}
@ -62,4 +73,27 @@ export class Native {
this.crychic.sendGroupPoke(memberUin, groupCode)
await this.ctx.ntMsgApi.fetchUnitedCommendConfig(['100243'])
}
uploadForward(peer: Peer, transmit: Uint8Array) {
return new Promise<string>(async (resolve, reject) => {
if (!this.crychic) return
let groupCode = 0
const uid = peer.peerUid
const isGroup = peer.chatType === ChatType.Group
if (isGroup) {
groupCode = +uid
}
const seq = ++this.seq
this.cb.set(seq, (resid: string) => {
this.cb.delete(seq)
resolve(resid)
})
setTimeout(() => {
this.cb.delete(seq)
reject(new Error('fake forward timeout'))
}, 5000)
this.crychic.uploadForward(seq, isGroup, uid, groupCode, transmit)
await this.ctx.ntMsgApi.fetchUnitedCommendConfig(['100243'])
})
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,134 @@
syntax = "proto3";
package Msg;
message RoutingHead {
optional uint64 fromUin = 1;
optional string fromUid = 2;
optional uint32 fromAppid = 3;
optional uint32 fromInstid = 4;
optional uint64 toUin = 5;
optional string toUid = 6;
optional C2c c2c = 7;
optional Group group = 8;
}
message C2c {
optional string friendName = 6;
}
message Group {
optional uint64 groupCode = 1;
optional uint32 groupType = 2;
optional uint64 groupInfoSeq = 3;
optional string groupCard = 4;
optional uint32 groupCardType = 5;
optional uint32 groupLevel = 6;
optional string groupName = 7;
optional string extGroupKeyInfo = 8;
optional uint32 msgFlag = 9;
}
message ContentHead {
optional uint64 msgType = 1;
optional uint64 subType = 2;
optional uint32 c2cCmd = 3;
optional uint64 random = 4;
optional uint64 msgSeq = 5;
optional uint64 msgTime = 6;
optional uint32 pkgNum = 7;
optional uint32 pkgIndex = 8;
optional uint32 divSeq = 9;
optional uint32 autoReply = 10;
optional uint64 ntMsgSeq = 11;
optional uint64 msgUid = 12;
optional ContentHeadField15 field15 = 15;
}
message ContentHeadField15 {
optional uint32 field1 = 1;
optional uint32 field2 = 2;
optional uint32 field3 = 3;
optional string field4 = 4;
optional string field5 = 5;
}
message Message {
optional RoutingHead routingHead = 1;
optional ContentHead contentHead = 2;
optional MessageBody body = 3;
}
message MessageBody {
optional RichText richText = 1;
optional bytes msgContent = 2;
optional bytes msgEncryptContent = 3;
}
message RichText {
optional Attr attr = 1;
repeated Elem elems = 2;
}
message Elem {
optional Text text = 1;
optional Face face = 2;
optional LightAppElem lightApp = 51;
optional CommonElem commonElem = 53;
}
message Text {
optional string str = 1;
optional string link = 2;
optional bytes attr6Buf = 3;
optional bytes attr7Buf = 4;
optional bytes buf = 11;
optional bytes pbReserve = 12;
}
message Face {
optional uint32 index = 1;
optional bytes old = 2;
optional bytes buf = 11;
}
message LightAppElem {
optional bytes data = 1;
optional bytes msgResid = 2;
}
message CommonElem {
required uint32 serviceType = 1;
optional bytes pbElem = 2;
optional uint32 businessType = 3;
}
message Attr {
optional int32 codePage = 1;
optional int32 time = 2;
optional int32 random = 3;
optional int32 color = 4;
optional int32 size = 5;
optional int32 effect = 6;
optional int32 charSet = 7;
optional int32 pitchAndFamily = 8;
optional string fontName = 9;
optional bytes reserveData = 10;
}
message MarkdownElem {
string content = 1;
}
message PbMultiMsgItem {
string fileName = 1;
PbMultiMsgNew buffer = 2;
}
message PbMultiMsgNew {
repeated Message msg = 1;
}
message PbMultiMsgTransmit {
repeated Message msg = 1;
repeated PbMultiMsgItem pbItemList = 2;
}

View File

@ -0,0 +1,76 @@
syntax = "proto3";
package RichMedia;
message MsgInfo {
repeated MsgInfoBody msgInfoBody = 1;
ExtBizInfo extBizInfo = 2;
}
message MsgInfoBody {
IndexNode index = 1;
PicInfo pic = 2;
bool fileExist = 5;
}
message IndexNode {
FileInfo info = 1;
string fileUuid = 2;
uint32 storeID = 3;
uint32 uploadTime = 4;
uint32 expire = 5;
uint32 type = 6; //0
}
message FileInfo {
uint32 fileSize = 1;
string md5HexStr = 2;
string sha1HexStr = 3;
string fileName = 4;
FileType fileType = 5;
uint32 width = 6;
uint32 height = 7;
uint32 time = 8;
uint32 original = 9;
}
message FileType {
uint32 type = 1;
uint32 picFormat = 2;
uint32 videoFormat = 3;
uint32 pttFormat = 4;
}
message PicInfo {
string urlPath = 1;
PicUrlExtParams ext = 2;
string domain = 3;
}
message PicUrlExtParams {
string originalParam = 1;
string bigParam = 2;
string thumbParam = 3;
}
message ExtBizInfo {
PicExtBizInfo pic = 1;
VideoExtBizInfo video = 2;
uint32 busiType = 10;
}
message PicExtBizInfo {
uint32 bizType = 1;
string summary = 2;
}
message VideoExtBizInfo {
bytes pbReserve = 3;
}
message PicFileIdInfo {
bytes sha1 = 2;
uint32 size = 3;
uint32 appid = 4;
uint32 time = 5;
uint32 expire = 10;
}

View File

@ -1,29 +0,0 @@
syntax = "proto3";
package SysMsg;
message SystemMessage {
repeated SystemMessageHeader header = 1;
repeated SystemMessageMsgSpec msgSpec = 2;
SystemMessageBodyWrapper bodyWrapper = 3;
}
message SystemMessageHeader {
uint32 peerUin = 1;
//string peerUid = 2;
uint32 uin = 5;
optional string uid = 6;
}
message SystemMessageMsgSpec {
uint32 msgType = 1;
optional uint32 subType = 2;
optional uint32 subSubType = 3;
uint32 msgSeq = 5;
uint32 time = 6;
//uint64 msgId = 12;
optional uint32 other = 13;
}
message SystemMessageBodyWrapper {
bytes body = 2;
}

View File

@ -80,7 +80,7 @@ export interface SendVideoElement {
export interface SendArkElement {
elementType: ElementType.Ark
elementId: ''
arkElement: ArkElement
arkElement: Partial<ArkElement>
}
export type SendMessageElement =
@ -587,3 +587,31 @@ export interface GetFileListParam {
showOnlinedocFolder: number
folderId?: string
}
export interface RichMediaUploadCompleteNotify {
fileId: string
fileDownType: number
filePath: string
totalSize: string
trasferStatus: number
commonFileInfo: {
uuid: string
fileName: string
fileSize: string
md5: string
sha: string
}
}
export enum RMBizType {
Unknown,
C2CFile,
GroupFile,
C2CPic,
GroupPic,
DiscPic,
C2CVideo,
GroupVideo,
C2CPtt,
GroupPtt,
}

View File

@ -1,11 +1,13 @@
import { unlink } from 'node:fs/promises'
import { OB11MessageNode } from '../../types'
import { OB11MessageData, OB11MessageNode } from '../../types'
import { ActionName } from '../types'
import { BaseAction, Schema } from '../BaseAction'
import { Peer } from '@/ntqqapi/types/msg'
import { ChatType, ElementType, RawMessage, SendMessageElement } from '@/ntqqapi/types'
import { selfInfo } from '@/common/globalVars'
import { convertMessage2List, createSendElements, sendMsg, createPeer, CreatePeerMode } from '../../helper/createMessage'
import { message2List, createSendElements, sendMsg, createPeer, CreatePeerMode } from '../../helper/createMessage'
import { MessageEncoder } from '@/onebot11/helper/createMultiMessage'
import { Msg } from '@/ntqqapi/proto/compiled'
interface Payload {
user_id?: string | number
@ -42,11 +44,91 @@ export class SendForwardMsg extends BaseAction<Payload, Response> {
contextMode = CreatePeerMode.Private
}
const peer = await createPeer(this.ctx, payload, contextMode)
const msg = await this.handleForwardNode(peer, messages)
const nodes = this.parseNodeContent(messages)
let fake = true
for (const node of nodes) {
if (node.data.id) {
fake = false
break
}
if (node.data.content?.some(e => {
return !MessageEncoder.support.includes(e.type)
})) {
fake = false
break
}
}
let msg: RawMessage
if (fake && this.ctx.app.native.activated) {
msg = await this.handleFakeForwardNode(peer, nodes)
} else {
msg = await this.handleForwardNode(peer, nodes)
}
const msgShortId = this.ctx.store.createMsgShortId({ chatType: msg.chatType, peerUid: msg.peerUid }, msg.msgId)
return { message_id: msgShortId }
}
private parseNodeContent(nodes: OB11MessageNode[]) {
return nodes.map(e => {
return {
type: e.type,
data: {
...e.data,
content: e.data.content ? message2List(e.data.content) : undefined
}
}
})
}
private async handleFakeForwardNode(peer: Peer, nodes: OB11MessageNode[]) {
const encoder = new MessageEncoder(this.ctx, peer)
const raw = await encoder.generate(nodes)
const transmit = Msg.PbMultiMsgTransmit.encode({ pbItemList: raw.multiMsgItems }).finish()
const resid = await this.ctx.app.native.uploadForward(peer, transmit.subarray(1))
const uuid = crypto.randomUUID()
try {
const msg = await this.ctx.ntMsgApi.sendMsg(peer, [{
elementType: 10,
elementId: '',
arkElement: {
bytesData: JSON.stringify({
app: 'com.tencent.multimsg',
config: {
autosize: 1,
forward: 1,
round: 1,
type: 'normal',
width: 300
},
desc: '[聊天记录]',
extra: JSON.stringify({
filename: uuid,
tsum: raw.tsum,
}),
meta: {
detail: {
news: raw.news,
resid,
source: raw.source,
summary: raw.summary,
uniseq: uuid,
}
},
prompt: '[聊天记录]',
ver: '0.0.0.5',
view: 'contact'
})
}
}], 1800)
return msg!
} catch (e) {
this.ctx.logger.error('合并转发失败', e)
throw new Error(`发送伪造合并转发消息失败 (res_id: ${resid} `)
}
}
private async cloneMsg(msg: RawMessage): Promise<RawMessage | undefined> {
this.ctx.logger.info('克隆的目标消息', msg)
const sendElements: SendMessageElement[] = []
@ -96,7 +178,7 @@ export class SendForwardMsg extends BaseAction<Payload, Response> {
try {
const { sendElements, deleteAfterSentFiles } = await createSendElements(
this.ctx,
convertMessage2List(messageNode.data.content),
messageNode.data.content as OB11MessageData[],
destPeer
)
this.ctx.logger.info('开始生成转发节点', sendElements)

View File

@ -9,7 +9,7 @@ import {
import { BaseAction } from '../BaseAction'
import { ActionName } from '../types'
import { CustomMusicSignPostData, IdMusicSignPostData, MusicSign, MusicSignPostData } from '@/common/utils/sign'
import { convertMessage2List, createSendElements, sendMsg, createPeer, CreatePeerMode } from '../../helper/createMessage'
import { message2List, createSendElements, sendMsg, createPeer, CreatePeerMode } from '../../helper/createMessage'
interface ReturnData {
message_id: number
@ -26,14 +26,14 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnData> {
contextMode = CreatePeerMode.Private
}
const peer = await createPeer(this.ctx, payload, contextMode)
const messages = convertMessage2List(
const messages = message2List(
payload.message,
payload.auto_escape === true || payload.auto_escape === 'true',
)
if (this.getSpecialMsgNum(messages, OB11MessageDataType.node)) {
if (this.getSpecialMsgNum(messages, OB11MessageDataType.Node)) {
throw new Error('请使用 /send_group_forward_msg 或 /send_private_forward_msg 进行合并转发')
}
else if (this.getSpecialMsgNum(messages, OB11MessageDataType.music)) {
else if (this.getSpecialMsgNum(messages, OB11MessageDataType.Music)) {
const music = messages[0] as OB11MessageMusic
if (music) {
const { musicSignUrl } = this.adapter.config
@ -78,7 +78,7 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnData> {
throw `签名音乐消息失败:${e}`
}
messages[0] = {
type: OB11MessageDataType.json,
type: OB11MessageDataType.Json,
data: { data: jsonContent },
} as OB11MessageJson
}

View File

@ -22,7 +22,7 @@ import { initActionMap } from './action'
import { llonebotError } from '../common/globalVars'
import { OB11GroupAdminNoticeEvent } from './event/notice/OB11GroupAdminNoticeEvent'
import { OB11ProfileLikeEvent } from './event/notice/OB11ProfileLikeEvent'
import { SysMsg } from '@/ntqqapi/proto/compiled'
import { Msg, SysMsg } from '@/ntqqapi/proto/compiled'
import { OB11GroupIncreaseEvent } from './event/notice/OB11GroupIncreaseEvent'
declare module 'cordis' {
@ -351,10 +351,10 @@ class OneBot11Adapter extends Service {
this.handleFriendRequest(input)
})
this.ctx.on('nt/system-message-created', async input => {
const sysMsg = SysMsg.SystemMessage.decode(input)
const { msgType, subType, subSubType } = sysMsg.msgSpec[0] ?? {}
if (msgType === 528 && subType === 39 && subSubType === 39) {
const tip = SysMsg.ProfileLikeTip.decode(sysMsg.bodyWrapper!.body!)
const sysMsg = Msg.Message.decode(input)
const { msgType, subType } = sysMsg.contentHead ?? {}
if (msgType === 528 && subType === 39) {
const tip = SysMsg.ProfileLikeTip.decode(sysMsg.body!.msgContent!)
if (tip.msgType !== 0 || tip.subType !== 203) return
const detail = tip.content?.msg?.detail
if (!detail) return
@ -362,7 +362,7 @@ class OneBot11Adapter extends Service {
const event = new OB11ProfileLikeEvent(detail.uin!, detail.nickname!, +times)
this.dispatch(event)
} else if (msgType === 33) {
const tip = SysMsg.GroupMemberChange.decode(sysMsg.bodyWrapper!.body!)
const tip = SysMsg.GroupMemberChange.decode(sysMsg.body!.msgContent!)
if (tip.type !== 130) return
this.ctx.logger.info('群成员增加', tip)
const memberUin = await this.ctx.ntUserApi.getUinByUid(tip.memberUid)

View File

@ -1,4 +1,3 @@
import { XMLParser } from 'fast-xml-parser'
import {
OB11Group,
OB11GroupMember,
@ -122,7 +121,7 @@ export namespace OB11Entities {
name = content.replace('@', '')
}
messageSegment = {
type: OB11MessageDataType.at,
type: OB11MessageDataType.At,
data: {
qq,
name
@ -135,7 +134,7 @@ export namespace OB11Entities {
continue
}
messageSegment = {
type: OB11MessageDataType.text,
type: OB11MessageDataType.Text,
data: {
text
}
@ -171,7 +170,7 @@ export namespace OB11Entities {
throw new Error('回复消息验证失败')
}
messageSegment = {
type: OB11MessageDataType.reply,
type: OB11MessageDataType.Reply,
data: {
id: ctx.store.createMsgShortId(peer, replyMsg ? replyMsg.msgId : records.msgId).toString()
}
@ -185,7 +184,7 @@ export namespace OB11Entities {
const { picElement } = element
const fileSize = picElement.fileSize ?? '0'
messageSegment = {
type: OB11MessageDataType.image,
type: OB11MessageDataType.Image,
data: {
file: picElement.fileName,
subType: picElement.picSubType,
@ -213,7 +212,7 @@ export namespace OB11Entities {
}, msg.msgId, element.elementId)
const fileSize = videoElement.fileSize ?? '0'
messageSegment = {
type: OB11MessageDataType.video,
type: OB11MessageDataType.Video,
data: {
file: videoElement.fileName,
url: videoUrl || pathToFileURL(videoElement.filePath).href,
@ -237,7 +236,7 @@ export namespace OB11Entities {
const { fileElement } = element
const fileSize = fileElement.fileSize ?? '0'
messageSegment = {
type: OB11MessageDataType.file,
type: OB11MessageDataType.File,
data: {
file: fileElement.fileName,
url: pathToFileURL(fileElement.filePath).href,
@ -262,7 +261,7 @@ export namespace OB11Entities {
const { pttElement } = element
const fileSize = pttElement.fileSize ?? '0'
messageSegment = {
type: OB11MessageDataType.voice,
type: OB11MessageDataType.Record,
data: {
file: pttElement.fileName,
url: pathToFileURL(pttElement.filePath).href,
@ -285,7 +284,7 @@ export namespace OB11Entities {
else if (element.arkElement) {
const { arkElement } = element
messageSegment = {
type: OB11MessageDataType.json,
type: OB11MessageDataType.Json,
data: {
data: arkElement.bytesData
}
@ -296,14 +295,14 @@ export namespace OB11Entities {
const { faceIndex, pokeType } = faceElement
if (faceIndex === FaceIndex.Dice) {
messageSegment = {
type: OB11MessageDataType.dice,
type: OB11MessageDataType.Dice,
data: {
result: faceElement.resultId!
}
}
} else if (faceIndex === FaceIndex.RPS) {
messageSegment = {
type: OB11MessageDataType.RPS,
type: OB11MessageDataType.Rps,
data: {
result: faceElement.resultId!
}
@ -315,7 +314,7 @@ export namespace OB11Entities {
}*/
} else {
messageSegment = {
type: OB11MessageDataType.face,
type: OB11MessageDataType.Face,
data: {
id: faceIndex.toString()
}
@ -331,7 +330,7 @@ export namespace OB11Entities {
// const url = `https://p.qpic.cn/CDN_STATIC/0/data/imgcache/htdocs/club/item/parcel/item/${dir}/${md5}/300x300.gif?max_age=31536000`
const url = `https://gxh.vip.qq.com/club/item/parcel/item/${dir}/${emojiId}/raw300.gif`
messageSegment = {
type: OB11MessageDataType.mface,
type: OB11MessageDataType.Mface,
data: {
summary: marketFaceElement.faceName!,
url,
@ -344,15 +343,15 @@ export namespace OB11Entities {
else if (element.markdownElement) {
const { markdownElement } = element
messageSegment = {
type: OB11MessageDataType.markdown,
type: OB11MessageDataType.Markdown,
data: {
data: markdownElement.content
content: markdownElement.content
}
}
}
else if (element.multiForwardMsgElement) {
messageSegment = {
type: OB11MessageDataType.forward,
type: OB11MessageDataType.Forward,
data: {
id: msg.msgId
}
@ -491,31 +490,27 @@ export namespace OB11Entities {
const xmlElement = grayTipElement.xmlElement
if (xmlElement?.templId === '10382') {
const emojiLikeData = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: '',
}).parse(xmlElement.content)
ctx.logger.info('收到表情回应我的消息', emojiLikeData)
ctx.logger.info('收到表情回应我的消息', xmlElement.templParam)
try {
const senderUin: string = emojiLikeData.gtip.qq.jp
const msgSeq: string = emojiLikeData.gtip.url.msgseq
const emojiId: string = emojiLikeData.gtip.face.id
const senderUin = xmlElement.templParam.get('jp_uin')
const msgSeq = xmlElement.templParam.get('msg_seq')
const emojiId = xmlElement.templParam.get('face_id')
const peer = {
chatType: ChatType.Group,
guildId: '',
peerUid: msg.peerUid,
}
const replyMsgList = (await ctx.ntMsgApi.queryFirstMsgBySeq(peer, msgSeq)).msgList
const replyMsgList = (await ctx.ntMsgApi.queryFirstMsgBySeq(peer, msgSeq!)).msgList
if (!replyMsgList?.length) {
return
}
const shortId = ctx.store.createMsgShortId(peer, replyMsgList[0].msgId)
return new OB11GroupMsgEmojiLikeEvent(
parseInt(msg.peerUid),
parseInt(senderUin),
parseInt(senderUin!),
shortId,
[{
emoji_id: emojiId,
emoji_id: emojiId!,
count: 1,
}]
)

View File

@ -33,14 +33,14 @@ export async function createSendElements(
continue
}
switch (sendMsg.type) {
case OB11MessageDataType.text: {
case OB11MessageDataType.Text: {
const text = sendMsg.data?.text
if (text) {
sendElements.push(SendElement.text(sendMsg.data!.text))
}
}
break
case OB11MessageDataType.at: {
case OB11MessageDataType.At: {
if (!peer) {
continue
}
@ -76,7 +76,7 @@ export async function createSendElements(
}
}
break
case OB11MessageDataType.reply: {
case OB11MessageDataType.Reply: {
if (sendMsg.data?.id) {
const info = await ctx.store.getMsgInfoByShortId(+sendMsg.data.id)
if (!info) {
@ -90,14 +90,14 @@ export async function createSendElements(
}
}
break
case OB11MessageDataType.face: {
case OB11MessageDataType.Face: {
const faceId = sendMsg.data?.id
if (faceId) {
sendElements.push(SendElement.face(parseInt(faceId)))
}
}
break
case OB11MessageDataType.mface: {
case OB11MessageDataType.Mface: {
sendElements.push(
SendElement.mface(
+sendMsg.data.emoji_package_id,
@ -108,10 +108,10 @@ export async function createSendElements(
)
}
break
case OB11MessageDataType.image: {
case OB11MessageDataType.Image: {
const res = await SendElement.pic(
ctx,
(await handleOb11FileLikeMessage(ctx, sendMsg, { deleteAfterSentFiles })).path,
(await handleOb11RichMedia(ctx, sendMsg, deleteAfterSentFiles)).path,
sendMsg.data.summary || '',
sendMsg.data.subType || 0,
sendMsg.data.type === 'flash'
@ -120,13 +120,13 @@ export async function createSendElements(
sendElements.push(res)
}
break
case OB11MessageDataType.file: {
const { path, fileName } = await handleOb11FileLikeMessage(ctx, sendMsg, { deleteAfterSentFiles })
case OB11MessageDataType.File: {
const { path, fileName } = await handleOb11RichMedia(ctx, sendMsg, deleteAfterSentFiles)
sendElements.push(await SendElement.file(ctx, path, fileName))
}
break
case OB11MessageDataType.video: {
const { path, fileName } = await handleOb11FileLikeMessage(ctx, sendMsg, { deleteAfterSentFiles })
case OB11MessageDataType.Video: {
const { path, fileName } = await handleOb11RichMedia(ctx, sendMsg, deleteAfterSentFiles)
let thumb = sendMsg.data.thumb
if (thumb) {
const uri2LocalRes = await uri2local(ctx, thumb)
@ -137,32 +137,32 @@ export async function createSendElements(
sendElements.push(res)
}
break
case OB11MessageDataType.voice: {
const { path } = await handleOb11FileLikeMessage(ctx, sendMsg, { deleteAfterSentFiles })
case OB11MessageDataType.Record: {
const { path } = await handleOb11RichMedia(ctx, sendMsg, deleteAfterSentFiles)
sendElements.push(await SendElement.ptt(ctx, path))
}
break
case OB11MessageDataType.json: {
case OB11MessageDataType.Json: {
sendElements.push(SendElement.ark(sendMsg.data.data))
}
break
case OB11MessageDataType.dice: {
case OB11MessageDataType.Dice: {
const resultId = sendMsg.data?.result
sendElements.push(SendElement.dice(resultId))
}
break
case OB11MessageDataType.RPS: {
case OB11MessageDataType.Rps: {
const resultId = sendMsg.data?.result
sendElements.push(SendElement.rps(resultId))
}
break
case OB11MessageDataType.contact: {
case OB11MessageDataType.Contact: {
const { type, id } = sendMsg.data
const data = type === 'qq' ? ctx.ntFriendApi.getBuddyRecommendContact(id) : ctx.ntGroupApi.getGroupRecommendContact(id)
sendElements.push(SendElement.ark(await data))
}
break
case OB11MessageDataType.shake: {
case OB11MessageDataType.Shake: {
sendElements.push(SendElement.shake())
}
break
@ -175,51 +175,22 @@ export async function createSendElements(
}
}
// forked from https://github.com/NapNeko/NapCatQQ/blob/6f6b258f22d7563f15d84e7172c4d4cbb547f47e/src/onebot11/action/msg/SendMsg/create-send-elements.ts#L26
async function handleOb11FileLikeMessage(
ctx: Context,
{ data: inputdata }: OB11MessageFileBase,
{ deleteAfterSentFiles }: { deleteAfterSentFiles: string[] },
) {
//有的奇怪的框架将url作为参数 而不是file 此时优先url 同时注意可能传入的是非file://开头的目录 By Mlikiowa
const {
path,
isLocal,
fileName,
errMsg,
success,
} = (await uri2local(ctx, inputdata.url || inputdata.file))
if (!success) {
ctx.logger.error(errMsg)
throw Error(errMsg)
}
if (!isLocal) { // 只删除http和base64转过来的文件
deleteAfterSentFiles.push(path)
}
return { path, fileName: inputdata.name || fileName }
}
export function convertMessage2List(message: OB11MessageMixType, autoEscape = false) {
export function message2List(message: OB11MessageMixType, autoEscape = false) {
if (typeof message === 'string') {
if (autoEscape === true) {
message = [
return [
{
type: OB11MessageDataType.text,
type: OB11MessageDataType.Text,
data: {
text: message,
},
},
]
] as OB11MessageData[]
} else {
return decodeCQCode(message)
}
else {
message = decodeCQCode(message.toString())
}
}
else if (!Array.isArray(message)) {
message = [message]
} else if (!Array.isArray(message)) {
return [message]
}
return message
}
@ -301,3 +272,18 @@ export async function createPeer(ctx: Context, payload: CreatePeerPayload, mode
}
throw new Error('请指定 group_id 或 user_id')
}
export async function handleOb11RichMedia(ctx: Context, segment: OB11MessageFileBase, deleteAfterSentFiles: string[]) {
const res = await uri2local(ctx, segment.data.url || segment.data.file)
if (!res.success) {
ctx.logger.error(res.errMsg)
throw Error(res.errMsg)
}
if (!res.isLocal) {
deleteAfterSentFiles.push(res.path)
}
return { path: res.path, fileName: segment.data.name || res.fileName }
}

View File

@ -0,0 +1,239 @@
import { Context } from 'cordis'
import { OB11MessageData, OB11MessageDataType } from '../types'
import { Msg, RichMedia } from '@/ntqqapi/proto/compiled'
import { handleOb11RichMedia } from './createMessage'
import { selfInfo } from '@/common/globalVars'
import { Peer, RichMediaUploadCompleteNotify } from '@/ntqqapi/types'
import { deflateSync } from 'node:zlib'
import faceConfig from '@/ntqqapi/helper/face_config.json'
export class MessageEncoder {
static support = ['text', 'face', 'image', 'markdown', 'forward']
results: Msg.Message[]
children: Msg.Elem[]
deleteAfterSentFiles: string[]
isGroup: boolean
seq: number
tsum: number
preview: string
news: { text: string }[]
name?: string
uin?: number
constructor(private ctx: Context, private peer: Peer) {
this.results = []
this.children = []
this.deleteAfterSentFiles = []
this.isGroup = peer.chatType === 2
this.seq = Math.trunc(Math.random() * 65430)
this.tsum = 0
this.preview = ''
this.news = []
}
async flush() {
if (this.children.length === 0) return
const nick = this.name || selfInfo.nick || 'QQ用户'
if (this.news.length < 4) {
this.news.push({
text: `${nick}: ${this.preview}`
})
}
this.results.push({
routingHead: {
fromUin: this.uin ?? +selfInfo.uin ?? 1094950020,
c2c: this.isGroup ? undefined : {
friendName: nick
},
group: this.isGroup ? {
groupCode: 284840486,
groupCard: nick
} : undefined
},
contentHead: {
msgType: this.isGroup ? 82 : 9,
random: Math.floor(Math.random() * 4294967290),
msgSeq: this.seq,
msgTime: Math.trunc(Date.now() / 1000),
pkgNum: 1,
pkgIndex: 0,
divSeq: 0,
field15: {
field1: 0,
field2: 0,
field3: 0,
field4: '',
field5: ''
}
},
body: {
richText: {
elems: this.children
}
}
})
this.seq++
this.tsum++
this.children = []
this.preview = ''
}
async packImage(data: RichMediaUploadCompleteNotify, busiType: number) {
const imageSize = await this.ctx.ntFileApi.getImageSize(data.filePath)
return {
commonElem: {
serviceType: 48,
pbElem: RichMedia.MsgInfo.encode({
msgInfoBody: [{
index: {
info: {
fileSize: +data.commonFileInfo.fileSize,
md5HexStr: data.commonFileInfo.md5,
sha1HexStr: data.commonFileInfo.sha,
fileName: data.commonFileInfo.fileName,
fileType: {
type: 1,
picFormat: imageSize.type === 'gif' ? 2000 : 1000
},
width: imageSize.width,
height: imageSize.height,
time: 0,
original: 1
},
fileUuid: data.fileId,
storeID: 1,
expire: 2678400
},
pic: {
urlPath: `/download?appid=${this.isGroup ? 1407 : 1406}&fileid=${data.fileId}`,
ext: {
originalParam: '&spec=0',
bigParam: '&spec=720',
thumbParam: '&spec=198'
},
domain: 'multimedia.nt.qq.com.cn'
},
fileExist: true
}],
extBizInfo: {
pic: {
bizType: 0,
summary: ''
},
busiType
}
}).finish(),
businessType: this.isGroup ? 20 : 10
}
}
}
packForwardMessage(resid: string) {
const uuid = crypto.randomUUID()
const content = JSON.stringify({
app: 'com.tencent.multimsg',
config: {
autosize: 1,
forward: 1,
round: 1,
type: 'normal',
width: 300
},
desc: '[聊天记录]',
extra: JSON.stringify({
filename: uuid,
tsum: 0,
}),
meta: {
detail: {
news: [{
text: '查看转发消息'
}],
resid,
source: '聊天记录',
summary: '查看转发消息',
uniseq: uuid,
}
},
prompt: '[聊天记录]',
ver: '0.0.0.5',
view: 'contact'
})
return {
lightApp: {
data: Buffer.concat([Buffer.from([1]), deflateSync(Buffer.from(content, 'utf-8'))])
}
}
}
async visit(segment: OB11MessageData) {
const { type, data } = segment
if (type === OB11MessageDataType.Node) {
await this.render(data.content as OB11MessageData[])
const id = data.id ?? data.user_id
this.uin = id ? +id : undefined
this.name = data.name ?? data.nickname
await this.flush()
} else if (type === OB11MessageDataType.Text) {
this.children.push({
text: {
str: data.text
}
})
this.preview += data.text
} else if (type === OB11MessageDataType.Face) {
this.children.push({
face: {
index: +data.id
}
})
const face = faceConfig.sysface.find(e => e.QSid === String(data.id))
if (face) {
this.preview += face.QDes
}
} else if (type === OB11MessageDataType.Image) {
const { path } = await handleOb11RichMedia(this.ctx, segment, this.deleteAfterSentFiles)
const data = await this.ctx.ntFileApi.uploadRMFileWithoutMsg(path, this.isGroup ? 4 : 3, this.peer.peerUid)
const busiType = Number(segment.data.subType) || 0
this.children.push(await this.packImage(data, busiType))
this.preview += busiType === 1 ? '[动画表情]' : '[图片]'
} else if (type === OB11MessageDataType.Markdown) {
this.children.push({
commonElem: {
serviceType: 45,
pbElem: Msg.MarkdownElem.encode(data).finish(),
businessType: 1
}
})
} else if (type === OB11MessageDataType.Forward) {
this.children.push(this.packForwardMessage(data.id))
this.preview += '[聊天记录]'
}
}
async render(segments: OB11MessageData[]) {
for (const segment of segments) {
await this.visit(segment)
}
}
async generate(content: any[]) {
await this.render(content)
return {
multiMsgItems: [{
fileName: 'MultiMsg',
buffer: {
msg: this.results
}
}],
tsum: this.tsum,
source: this.isGroup ? '群聊的聊天记录' : '聊天记录',
summary: `查看${this.tsum}条转发消息`,
news: this.news
}
}
}

View File

@ -2,7 +2,7 @@ import { OB11Message, OB11MessageData, OB11MessageDataType } from '../types'
import { OB11FriendRequestEvent } from '../event/request/OB11FriendRequest'
import { OB11GroupRequestEvent } from '../event/request/OB11GroupRequest'
import { GroupRequestOperateTypes } from '@/ntqqapi/types'
import { convertMessage2List, createSendElements, sendMsg, createPeer, CreatePeerMode } from '../helper/createMessage'
import { message2List, createSendElements, sendMsg, createPeer, CreatePeerMode } from '../helper/createMessage'
import { isNullable } from 'cosmokit'
import { Context } from 'cordis'
@ -65,7 +65,7 @@ async function handleMsg(ctx: Context, msg: OB11Message, quickAction: QuickOpera
if (reply) {
let replyMessage: OB11MessageData[] = []
replyMessage.push({
type: OB11MessageDataType.reply,
type: OB11MessageDataType.Reply,
data: {
id: msg.message_id.toString(),
},
@ -74,14 +74,14 @@ async function handleMsg(ctx: Context, msg: OB11Message, quickAction: QuickOpera
if (msg.message_type == 'group') {
if ((quickAction as QuickOperationGroupMessage).at_sender) {
replyMessage.push({
type: OB11MessageDataType.at,
type: OB11MessageDataType.At,
data: {
qq: msg.user_id.toString(),
},
})
}
}
replyMessage = replyMessage.concat(convertMessage2List(reply, quickAction.auto_escape))
replyMessage = replyMessage.concat(message2List(reply, quickAction.auto_escape))
const { sendElements, deleteAfterSentFiles } = await createSendElements(ctx, replyMessage, peer)
sendMsg(ctx, peer, sendElements, deleteAfterSentFiles).catch(e => ctx.logger.error(e))
}

View File

@ -117,30 +117,30 @@ export interface OB11Return<DataType> {
}
export enum OB11MessageDataType {
text = 'text',
image = 'image',
music = 'music',
video = 'video',
voice = 'record',
file = 'file',
at = 'at',
reply = 'reply',
json = 'json',
face = 'face',
mface = 'mface', // 商城表情
markdown = 'markdown',
node = 'node', // 合并转发消息节点
forward = 'forward', // 合并转发消息,用于上报
xml = 'xml',
poke = 'poke',
dice = 'dice',
RPS = 'rps',
contact = 'contact',
shake = 'shake',
Text = 'text',
Image = 'image',
Music = 'music',
Video = 'video',
Record = 'record',
File = 'file',
At = 'at',
Reply = 'reply',
Json = 'json',
Face = 'face',
Mface = 'mface', // 商城表情
Markdown = 'markdown',
Node = 'node', // 合并转发消息节点
Forward = 'forward', // 合并转发消息,用于上报
Xml = 'xml',
Poke = 'poke',
Dice = 'dice',
Rps = 'rps',
Contact = 'contact',
Shake = 'shake',
}
export interface OB11MessageMFace {
type: OB11MessageDataType.mface
type: OB11MessageDataType.Mface
data: {
emoji_package_id: number
emoji_id: string
@ -151,27 +151,27 @@ export interface OB11MessageMFace {
}
export interface OB11MessageDice {
type: OB11MessageDataType.dice
type: OB11MessageDataType.Dice
data: {
result: number /* intended */ | string /* in fact */
}
}
export interface OB11MessageRPS {
type: OB11MessageDataType.RPS
type: OB11MessageDataType.Rps
data: {
result: number | string
}
}
export interface OB11MessageText {
type: OB11MessageDataType.text
type: OB11MessageDataType.Text
data: {
text: string // 纯文本
}
}
export interface OB11MessagePoke {
type: OB11MessageDataType.poke
type: OB11MessageDataType.Poke
data: {
qq?: number
id?: number
@ -189,7 +189,7 @@ export interface OB11MessageFileBase {
}
export interface OB11MessageImage extends OB11MessageFileBase {
type: OB11MessageDataType.image
type: OB11MessageDataType.Image
data: OB11MessageFileBase['data'] & {
summary?: string // 图片摘要
subType?: PicSubType
@ -198,14 +198,14 @@ export interface OB11MessageImage extends OB11MessageFileBase {
}
export interface OB11MessageRecord extends OB11MessageFileBase {
type: OB11MessageDataType.voice
type: OB11MessageDataType.Record
data: OB11MessageFileBase['data'] & {
path?: string //扩展
}
}
export interface OB11MessageFile extends OB11MessageFileBase {
type: OB11MessageDataType.file
type: OB11MessageDataType.File
data: OB11MessageFileBase['data'] & {
file_id?: string
path?: string
@ -213,14 +213,14 @@ export interface OB11MessageFile extends OB11MessageFileBase {
}
export interface OB11MessageVideo extends OB11MessageFileBase {
type: OB11MessageDataType.video
type: OB11MessageDataType.Video
data: OB11MessageFileBase['data'] & {
path?: string //扩展
}
}
export interface OB11MessageAt {
type: OB11MessageDataType.at
type: OB11MessageDataType.At
data: {
qq: string | 'all'
name?: string
@ -228,14 +228,14 @@ export interface OB11MessageAt {
}
export interface OB11MessageReply {
type: OB11MessageDataType.reply
type: OB11MessageDataType.Reply
data: {
id: string
}
}
export interface OB11MessageFace {
type: OB11MessageDataType.face
type: OB11MessageDataType.Face
data: {
id: string
}
@ -244,48 +244,50 @@ export interface OB11MessageFace {
export type OB11MessageMixType = OB11MessageData[] | string | OB11MessageData
export interface OB11MessageNode {
type: OB11MessageDataType.node
type: OB11MessageDataType.Node
data: {
id?: string
user_id?: number
nickname: string
content: OB11MessageMixType
id?: number | string
content?: OB11MessageMixType
user_id?: number // ob11
nickname?: string // ob11
name?: string // gocq
uin?: number | string // gocq
}
}
export interface OB11MessageIdMusic {
type: OB11MessageDataType.music
type: OB11MessageDataType.Music
data: IdMusicSignPostData
}
export interface OB11MessageCustomMusic {
type: OB11MessageDataType.music
type: OB11MessageDataType.Music
data: Omit<CustomMusicSignPostData, 'singer'> & { content?: string }
}
export type OB11MessageMusic = OB11MessageIdMusic | OB11MessageCustomMusic
export interface OB11MessageJson {
type: OB11MessageDataType.json
type: OB11MessageDataType.Json
data: { data: string /* , config: { token: string } */ }
}
export interface OB11MessageMarkdown {
type: OB11MessageDataType.markdown
type: OB11MessageDataType.Markdown
data: {
data: string
content: string
}
}
export interface OB11MessageForward {
type: OB11MessageDataType.forward
type: OB11MessageDataType.Forward
data: {
id: string
}
}
export interface OB11MessageContact {
type: OB11MessageDataType.contact
type: OB11MessageDataType.Contact
data: {
type: 'qq' | 'group'
id: string
@ -293,7 +295,7 @@ export interface OB11MessageContact {
}
export interface OB11MessageShake {
type: OB11MessageDataType.shake
type: OB11MessageDataType.Shake
data: Record<string, never>
}