-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(dingtalk): decode message, markdown content
- Loading branch information
1 parent
2d796a1
commit dcb269e
Showing
5 changed files
with
233 additions
and
33 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,137 @@ | ||
import { h, MessageEncoder } from '@satorijs/satori' | ||
import { Dict, h, MessageEncoder } from '@satorijs/satori' | ||
import { DingtalkBot } from './bot' | ||
import FormData from 'form-data' | ||
import { SendMessageData } from './types' | ||
|
||
export const escape = (val: string) => | ||
val | ||
.replace(/(?<!\u200b)[\*_~`]/g, '\u200B$&') | ||
.replace(/([\\`*_{}[\]\-(#!>])/g, '\\$&') | ||
.replace(/([\-\*]|\d\.) /g, '\u200B$&') | ||
.replace(/^(\s{4})/gm, '\u200B ') | ||
|
||
export const unescape = (val: string) => | ||
val | ||
.replace(/\u200b([\*_~`])/g, '$1') | ||
|
||
export class DingtalkMessageEncoder extends MessageEncoder<DingtalkBot> { | ||
buffer = '' | ||
|
||
/** | ||
* Markdown: https://open.dingtalk.com/document/isvapp/robot-message-types-and-data-format | ||
*/ | ||
|
||
hasRichContent = true | ||
async flush(): Promise<void> { | ||
console.log(await this.bot.http.post('/robot/groupMessages/send', { | ||
// https://open.dingtalk.com/document/orgapp/types-of-messages-sent-by-robots | ||
msgKey: 'sampleText', | ||
msgParam: JSON.stringify({ | ||
if (this.buffer.length && !this.hasRichContent) { | ||
await this.sendMessage("sampleText", { | ||
content: this.buffer | ||
}), | ||
}) | ||
} else if (this.buffer.length && this.hasRichContent) { | ||
await this.sendMessage("sampleMarkdown", { | ||
text: this.buffer.replace(/\n/g, '\n\n') | ||
}) | ||
} | ||
} | ||
|
||
// https://open.dingtalk.com/document/orgapp/the-robot-sends-a-group-message | ||
async sendMessage<T extends keyof SendMessageData>(msgType: T, msgParam: SendMessageData[T]) { | ||
console.log(this.session) | ||
const { processQueryKey } = await this.bot.http.post( | ||
this.session.isDirect ? '/robot/oToMessages/batchSend' : '/robot/groupMessages/send', { | ||
// https://open.dingtalk.com/document/orgapp/types-of-messages-sent-by-robots | ||
msgKey: msgType, | ||
msgParam: JSON.stringify(msgParam), | ||
robotCode: this.bot.config.appkey, | ||
openConversationId: this.channelId | ||
})) | ||
...this.session.isDirect ? { | ||
userIds: [this.session.channelId] | ||
} : { | ||
openConversationId: this.channelId | ||
} | ||
}) | ||
const session = this.bot.session() | ||
session.messageId = processQueryKey | ||
this.results.push(session) | ||
} | ||
|
||
// https://open.dingtalk.com/document/orgapp/upload-media-files?spm=ding_open_doc.document.0.0.3b166172ERBuHw | ||
async uploadMedia(attrs: Dict) { | ||
const { data, mime } = await this.bot.ctx.http.file(attrs.url, attrs) | ||
const form = new FormData() | ||
// https://github.com/form-data/form-data/issues/468 | ||
const value = process.env.KOISHI_ENV === 'browser' | ||
? new Blob([data], { type: mime }) | ||
: Buffer.from(data) | ||
let type; | ||
if (mime.startsWith("image/") || mime.startsWith("video/")) { | ||
type = mime.split("/")[0] | ||
} else if (mime.startsWith("audio/")) { | ||
type = "voice" | ||
} else { | ||
type = "file" | ||
} | ||
form.append("type", type) | ||
form.append('media', value) | ||
const { media_id } = await this.bot.oldHttp.post('/media/upload', form, { | ||
headers: form.getHeaders() | ||
}) | ||
return media_id | ||
} | ||
|
||
private listType: 'ol' | 'ul' = null | ||
|
||
async visit(element: h) { | ||
const { type, attrs, children } = element | ||
|
||
if (type === 'text') { | ||
this.buffer += attrs.content | ||
console.log(attrs.content) | ||
this.buffer += escape(attrs.content) | ||
} else if (type === 'image' && attrs.url) { | ||
// await this.flush() | ||
// await this.sendMessage('sampleImageMsg', { | ||
// photoURL: attrs.url | ||
// }) | ||
this.buffer += `![${attrs.alt}](${attrs.url})` | ||
} else if (type === 'message') { | ||
await this.flush() | ||
await this.render(children) | ||
} else if (type === 'at') { | ||
this.buffer += `@${attrs.id}` | ||
} else if (type === 'p') { | ||
this.buffer += '\n' | ||
await this.render(children) | ||
this.buffer += '\n' | ||
} else if (type === 'b' || type === 'strong') { | ||
this.buffer += ` **` | ||
await this.render(children) | ||
this.buffer += `** ` | ||
} else if (type === 'i' || type === 'em') { | ||
this.buffer += ` *` | ||
await this.render(children) | ||
this.buffer += `* ` | ||
} else if (type === 'a' && attrs.href) { | ||
this.buffer += `[` | ||
console.log(children) | ||
await this.render(children) | ||
this.buffer += `](${encodeURI(attrs.href)})` | ||
} else if (type === 'ul' || type === 'ol') { | ||
this.listType = type | ||
await this.render(children) | ||
this.listType = null | ||
} else if (type === 'li') { | ||
if (!this.buffer.endsWith('\n')) this.buffer += '\n' | ||
if (this.listType === 'ol') { | ||
this.buffer += `1. ` | ||
} else if (this.listType === 'ul') { | ||
this.buffer += '- ' | ||
} | ||
this.render(children) | ||
this.buffer += '\n' | ||
} else if (type === 'blockquote') { | ||
console.log(children) | ||
if (!this.buffer.endsWith('\n')) this.buffer += '\n' | ||
this.buffer += '> ' | ||
await this.render(children) | ||
this.buffer += '\n\n' | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,43 @@ | ||
import { h, Session } from '@satorijs/satori' | ||
import { Message } from './types'; | ||
import { DingtalkBot } from './bot'; | ||
|
||
export async function decodeMessage(bot: DingtalkBot, body: Message): Promise<Session> { | ||
const session = bot.session() | ||
session.type = "message" | ||
session.messageId = body.msgId | ||
session.isDirect = body.conversationType === "1" | ||
session.guildId = body.chatbotCorpId | ||
|
||
if (body.conversationTitle) session.channelName = body.conversationTitle | ||
session.userId = body.senderStaffId | ||
session.author = { | ||
userId: body.senderStaffId, | ||
username: body.senderNick, | ||
roles: body.isAdmin ? ['admin'] : [], | ||
} | ||
session.timestamp = Number(body.createAt) | ||
if (body.msgtype === "text") { | ||
session.elements = [h.text(body.text.content)] | ||
} else if (body.msgtype === 'richText') { | ||
let elements: h[] = [] | ||
for (const item of body.content.richText) { | ||
if (item.text) elements.push(h.text(item.text)) | ||
if (item.downloadCode) { | ||
const url = await bot.downloadFile(item.downloadCode) | ||
elements.push(h.image(url)) | ||
} | ||
} | ||
session.elements = elements | ||
} else { | ||
return | ||
} | ||
if (!session.isDirect) { | ||
// group message | ||
session.elements = [h.at(body.robotCode), ...session.elements] | ||
session.channelId = body.conversationId | ||
} else { | ||
session.channelId = session.userId | ||
} | ||
return session | ||
} |