diff --git a/adapters/discord/src/message.ts b/adapters/discord/src/message.ts index 36afb7cf..69e00e39 100644 --- a/adapters/discord/src/message.ts +++ b/adapters/discord/src/message.ts @@ -1,7 +1,7 @@ import { Context, Dict, h, MessageEncoder, Schema, Universal } from '@satorijs/core' import { DiscordBot } from './bot' import { ActionRow, Button, ButtonStyles, Channel, ComponentType, Message } from './types' -import { decodeMessage, sanitize } from './utils' +import { decodeMessage, sanitize, sanitizeCode } from './utils' type RenderMode = 'default' | 'figure' @@ -230,9 +230,13 @@ export class DiscordMessageEncoder extends MessageE await this.render(children) this.buffer += '||' } else if (type === 'code') { - this.buffer += '`' - await this.render(children) - this.buffer += '`' + this.buffer += '``' + this.buffer += sanitizeCode(children.toString()) + this.buffer += '``' + } else if (type === 'code-block') { + this.buffer += `\`\`\`${attrs.language ?? ''}\n` + this.buffer += sanitizeCode(children.toString()) + this.buffer += '\n```' } else if (type === 'a') { this.buffer += '[' await this.render(children) diff --git a/adapters/discord/src/utils.ts b/adapters/discord/src/utils.ts index 26c485fe..f99b004c 100644 --- a/adapters/discord/src/utils.ts +++ b/adapters/discord/src/utils.ts @@ -10,6 +10,10 @@ export const sanitize = (val: string) => .replace(/@everyone/g, () => '\\@everyone') .replace(/@here/g, () => '\\@here') +// discord has no way to escape ` in code/codeblock, so we use zero-width space as a fallback. +// we don't need or have to do any escape other than ` in code/codeblock. +export const sanitizeCode = (val: string) => val.replace(/(?<=`)(?=`)/g, '\u200b') + export const decodeUser = (user: Discord.User): Universal.User => ({ id: user.id, name: user.username,